简体   繁体   English

将JSON数组插入mongodb

[英]Insert JSON Array into mongodb

I'm trying to insert a string that represents a JSON array into a mongodb collection with this, 我正在尝试将表示JSON数组的字符串插入到mongodb集合中,

String str = "[{\"id\":1,\"data\":\"data1\"},{\"id\":2,\"data\":\"data2\"},{\"id\":3,\"data\":\"data3\"}]";
DBObject dbObject = (DBObject) JSON.parse(str);
collection.insert(dbObject);

But I get the exception, 但我得到例外,

Exception in thread "main" java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [_id]

Can anyone show me the correct way to do this? 有谁能告诉我这样做的正确方法?

String json = "[{\"id\":1,\"data\":\"data1\"},{\"id\":2,\"data\":\"data2\"},{\"id\":3,\"data\":\"data3\"}]";
    MongoCredential credential = MongoCredential.createCredential("root", "sample", "root".toCharArray());
    MongoClient mongoClient = new MongoClient(new ServerAddress("localhost"), Arrays.asList(credential));
    MongoDatabase db = mongoClient.getDatabase("sample");
    MongoCollection<Document> collection = db.getCollection("loginTracking");
    List<Document> jsonList = new ArrayList<Document>();
    net.sf.json.JSONArray array = net.sf.json.JSONArray.fromObject(json);
    for (Object object : array) {
        net.sf.json.JSONObject jsonStr = (net.sf.json.JSONObject) JSONSerializer.toJSON(object);
        Document jsnObject = Document.parse(jsonStr.toString());
        jsonList.add(jsnObject);

    }
    collection.insertMany(jsonList);
    mongoClient.close();

as per java doc the insert() can accept either single DBObject or an array or List of them. 根据java docinsert()可以接受单个DBObject或它们的数组或List

So, in order to save, you need to convert your JSON array into an array/List of DBObjects, or save each array's item 因此,为了保存,您需要将JSON数组转换为数组/ DBObject列表,或者保存每个数组的项目

I found a good way for achieve that: 我找到了实现这个目标的好方法:

(ArrayList<Document>) JSON.parse("[String json array]");

I had a problem with this, because i need append to this document a property that is a Json Array: 我有一个问题,因为我需要在这个文档中附加一个Json数组的属性:

Document objAddendumVersion = new Document();
objAddendumVersion.append("_id", new ObjectId());
objAddendumVersion.append("Array", My Array here!);

But the problem is that Document.parse() doesn't work with Arrays, so i could solve it using the above line. 但问题是Document.parse()不适用于Arrays,所以我可以使用上面的行来解决它。 So the final code is: 所以最终的代码是:

Document objAddendumVersion = new Document();
objAddendumVersion.append("_id", new ObjectId());
objAddendumVersion.append("Array", (ArrayList<Document>) JSON.parse("[String json array]"));

And it works perfect. 它完美无缺。 Yes i know that exist more better ways for do that, but for the moment i'm using this. 是的,我知道存在更好的方法,但目前我正在使用它。

I wait that be useful for someone with the same trouble. 我等待对有同样麻烦的人有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM