Perform Bulk insert in MongoDB?


For bulk insert in MongoDB, use initializeUnorderedBulkOp(). Let us create a collection with documents −

> var bulkInsertDoc = db.demo663.initializeUnorderedBulkOp();
> bulkInsertDoc.insert( { Name: "John",CountryName:"US"} );
> bulkInsertDoc.insert( { Name: "Chris",CountryName:"UK"} );
> bulkInsertDoc.insert( { Name: "David",CountryName:"AUS"} );
> bulkInsertDoc.execute();
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 3,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})

Display all documents from a collection with the help of find() method −

> db.demo663.find();

This will produce the following output −

{ "_id" : ObjectId("5ea1b41424113ea5458c7d05"), "Name" : "John", "CountryName" : "US" }
{ "_id" : ObjectId("5ea1b41424113ea5458c7d06"), "Name" : "Chris", "CountryName" : "UK" }
{ "_id" : ObjectId("5ea1b41424113ea5458c7d07"), "Name" : "David", "CountryName" : "AUS" }

Updated on: 13-May-2020

336 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements