简体   繁体   中英

Insert JSON Array into mongodb

I'm trying to insert a string that represents a JSON array into a mongodb collection with this,

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.

So, in order to save, you need to convert your JSON array into an array/List of DBObjects, or save each array's item

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:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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