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 DBObject
s for inserting multiple documents at once. You are passing in a string array.
You must manually populate documents(DBObject
s), insert them to a List<DBObject>
or an array of DBObject
s 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"} ]);
Before 3.0, you can use below code in Java
DB db = mongoClient.getDB("yourDB"); DBCollection coll = db.getCollection("yourCollection"); BulkWriteOperation builder = coll.initializeUnorderedBulkOperation(); for(DBObject doc :yourList) { builder.insert(doc); } BulkWriteResult result = builder.execute(); return result.isAcknowledged();
If you are using mongodb version 3.0 , you can use
MongoDatabase database = mongoClient.getDatabase("yourDB"); MongoCollection<Document> collection = database.getCollection("yourCollection"); collection.insertMany(yourDocumentList);
As of MongoDB 2.6 and 2.12 version of the driver you can also now do a bulk insert operation. In Java you could use the BulkWriteOperation. An example use of this could be:
DBCollection coll = db.getCollection("user");BulkWriteOperation bulk = coll.initializeUnorderedBulkOperation();bulk.find(new BasicDBObject("z", 1)).upsert().update(new BasicDBObject("$inc", new BasicDBObject("y", -1)));bulk.find(new BasicDBObject("z", 1)).upsert().update(new BasicDBObject("$inc", new BasicDBObject("y", -1)));bulk.execute();