mongodb bulk insert

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Previously, we saw how mongodb insert query can be used for inserting documents. This will deal with mongodb bulk insert operation which can be used to insert multiple document at once. It is like a batch process.

Mongodb Bulk Insert:

For inserting multiple records at once, we need a Bulk builder for the collection. Consider below code

> var bulk = db.employees.initializeUnorderedBulkOp();

  • var bulk defines a variable called bulk.
  • db is a default variable which refers to current database.
  • employees is the collection for which we are going to create Bulk builder
  • initializeUnorderedBulkOp is the methods that returns Bulk builder which will be used for mongoDB bulk insert.

Now after we got the builder, we can insert documents into builder one by one.

insert operation has not been completed yet. Right now documents are only in bulk builder. To complete mongodb bulk insert, you need to execute the bulk as below.

it will return an object of type BulkWriteResult. as below.

This mongodb bulk insert operation confirms that 3 documents are inserted with zero errors.

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Leave a Reply

Your email address will not be published. Required fields are marked *