How to insert multiple documents at once in MongoDB through Java

DBCollection.insert accepts a parameter of type DBObject, List<DBObject> or an array of DBObjects for inserting multiple documents at once. You are passing in a string array.

You must manually populate documents(DBObjects), insert them to a List<DBObject> or an array of DBObjects and eventually insert them.

DBObject document1 = new BasicDBObject();
document1.put("name", "Kiran");
document1.put("age", 20);

DBObject document2 = new BasicDBObject();
document2.put("name", "John");

List<DBObject> documents = new ArrayList<>();
documents.add(document1);
documents.add(document2);
collection.insert(documents);

The above snippet is essentially the same as the command you would issue in the MongoDB shell:

db.people.insert( [ {name: "Kiran", age: 20}, {name: "John"} ]);

Leave a Comment