Insert json array in mongodb

I am trying to insert a string representing a JSON array into the 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 an exception

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

Can someone show me the correct way to do this?

+5
source share
3 answers

according to java doc insert() can only take one DBObject or an array or List of them.

So, to save, you need to convert your JSON array to an array / DBObjects List or save each element of the array

+1
source
 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(); 
+1
source

I found a good way to achieve this:

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

I had a problem with this because I need to add a property to this document, which 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 () does not work with arrays, so I can solve it using the line above. 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 great. Yes, I know that there are more effective ways to do this, but at the moment I'm using it.

I am expecting it to be useful for someone with the same problem.

0
source

Source: https://habr.com/ru/post/1211922/


All Articles