How to add an array to a MongoDB document using Java? How to add an array to a MongoDB document using Java? mongodb mongodb

How to add an array to a MongoDB document using Java?


Change to something like this:

testObject.put("suitename", testsuite);testObject.put("testname", testcase);         List<BasicDBObject> milestones = new ArrayList<>();milestones.add(new BasicDBObject("milestone_id", "2333"));testObject.put("milestones", milestones);locations.insert(testObject);


You can create an ArrayList which takes in DBObjects.

List<DBObject> array = new ArrayList<DBObject>();

Add the created DBObject for the object inside the array and add it to the array object created.

array.add(/* some object */);

Finally, put the array in the main document object.

document.put("milestones", array);


Better use:

MongoClient client = new MongoClient("localhost",27017);MongoCollection<Document> collection =        client.getDatabase("db").getCollection("collection");List<Document> docs=new ArrayList<>();docs.add();collection.insertMany(docs);client.close();