Unordered Insertion of documents
Now, let’s use the below commands to make an object of Bulk using initializeUnorderedBulkOp() and use Bulk.insert() to insert multiple documents. Here, the initializeUnorderedBulkOp() method is used to generate an unordered list that MongoDB runs in bulk.
var bulk = db.students.initializeUnorderedBulkOp();
bulk.insert( { first_name: "Sachin", last_name: "Tendulkar" } );
bulk.insert( { first_name: "Virender", last_name: "Sehwag" } );
bulk.insert( { first_name: "Shikhar", last_name: "Dhawan" } );
bulk.insert( { first_name: "Mohammed", last_name: "Shami" } );
bulk.insert( { first_name: "Shreyas", last_name: "Iyer" } );
bulk.execute();
Let’s check the inserted documents using the below command:
db.students.find();
MongoDB – Bulk.insert() Method
In MongoDB, the Bulk.insert() method is used to perform insert operations in bulk. Or in other words, the Bulk.insert() method is used to insert multiple documents in one go. To use Bulk.insert() method the collection in which data has to be inserted must already exist.
We will discuss the following two types of insertion:
Table of Content
- Unordered Insertion of documents
- Ordered Insertion of documents
Syntax:
Bulk.insert(<document>);
Parameter:
document: The document that has to be inserted.
Examples:
In the following examples, we are working with:
Database: myDatabase
Collection: students