Open In App

MongoDB – bulkWrite() Method

MongoDB is a versatile document-based NoSQL database and can perform DB write operations efficiently using its bulkWrite() method.

The db.collection.bulkWrite() method allows multiple documents to be inserted/updated/deleted at once.



Important Points:

Syntax

db.collection.bulkWrite(
[ <opr1>, <opr2>, ...,<oprn> ],
{
     writeConcern : <your document and this is optional>,
     ordered : <true/false, defaults to true and this is optional>
}
)

Parameters:

Return:

This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled), count for every write operation, and an array that contains an _id for every successfully inserted or upserted document.

MongoDB bulkWrite() Method Operations

Now let us understand the write operations:



In the following write operations, we are working with:

Database: studentsdb

Collection: students

Document: three documents that contain the details of the students.

1. insertOne Operation Example:

insertOne is used to insert one document in the collection.

Syntax:

db.collection.bulkWrite([{insertOne: {“document” : <document>}}])

Example:

Let us apply the insertion of 2 documents and check the output of it:

try{
… db.students.bulkWrite([
… {insertOne:{“document”:{studentId:4, studentName:”GeekD”, studentAge:24}}},
… {insertOne:{“document”:{studentId:4, studentName:”GeekD”, studentAge:24}}}
… ]);
… }catch(e){
… print(e);
… }

As the above query contains two “insertOne” statements, 2 documents were inserted properly. Here, “insertedids’ represents the values that got inserted. Now, in the execution of find(), we can see the new documents are inserted perfectly

The “_id” column is the unique one to identify the document. In our example, for _id, randomly the value is picked. We can explicitly set the value of _id to 1, 2, etc., _id column behaves like the Primary key concept so, we are not allowed to insert duplicate rows.

2. updateOne and updateMany Operation Example

updateOne is used to update one document in the collection.

Syntax:

db.collection.bulkWrite([{updateOne
{“filter”: <document>,
“update”:<document>,
“upsert”:<boolean>,
“collation”:<document>,
“arrayFilters”:[<filterdocument1>, <filterdocument2>,..]
“hint”:<document|string>
}
}])

Example:

We need to provide valid filter conditions i.e. need to check the columns correctly (MongoDB case-sensitive) and provide the columns to be updated.

try {
db.students.bulkWrite([
{ updateOne : {
"filter" : { "studentId" : 2 },
"update" : { $set : { "studentName" : "GeekyBest" } }
} }
]);
} catch (e) {
print(e);
}

Output:

Here, first “filtered” for “studentId = 2” and if present, updated the “studentName” to “GeekyBest” by using “updateOne”. If multiple documents match the given filtration, then “updateOne”, updates the first document that matches the given condition in the collection. 

Hence, in the above process, for one document, the update is done. “studentId” and “studentid” are treated differently because MongoDB is case-sensitive.

updateMany is used to update all the documents that match the given condition in the collection.

Syntax:

db.collection.bulkWrite([{updateMany
{“filter”: <document>,
“update”:<document>,
“upsert”:<boolean>,
“collation”:<document>,
“arrayFilters”:[<filterdocument1>, <filterdocument2>,..]
“hint”:<document|string>
}
}])

Example:

try {
db.students.bulkWrite([
{ updateMany : {
"filter" : { "studentId" : 4 },
"update" : { $set : { "studentName" : "GeeksForGeeksbest" } }
} }
]);
} catch (e) {
print(e);
}

“matchedCount” represents how many documents got matched and it shows 1 because 1 document matched for the filtered condition and hence the matched document “studentName” got changed.

3. replaceOne Operation Example

replaceOne replaces a single document according to the match that is provided in the filter. Even when multiple documents are matched, replaceOne will always replace the first matched document.

Syntax:

db.collection.bulkWrite([{replaceOne : 
{“filter”: <document>,
“replacement”:<document>,
“upsert”:<boolean>,
“collation”:<document>,
“hint”:<document|string>
}
}])

Example:

try {
db.students.bulkWrite([
{ replaceOne : {
"filter" : { "studentId" : 3 },
"replacement" : { "studentId" : 30, "studentName" : "BestGeek" }
} }
]);
} catch (e) {
print(e);
}

In the above example, we checked for “studentId = 3” and one document is matched the given filter and the following replacements are done i.e. “studentId = 30 and studentName = BestGeek” are the replacements done and they are replaced also.

4. deleteOne and deleteMany Operation:

deleteOne deletes a single document according to the match that is provided in the filter. Even when multiple documents are matched, deleteOne will always delete the first matching document.

Syntax:

db.collection.bulkWrite([{deleteOne : 
{“filter”: <document>,
“collation”:<document>
}
}])

Example:

try {
db.students.bulkWrite([
{ deleteOne : { "filter" : { "studentId" : 30} } }
]);
} catch (e) {
print(e);
}

Here, “deleteone” will delete a document that matches the given filter(i.e,”studentId” : 30)

deleteMany will delete all the documents that are matching. Hence, it depends upon the requirement, we need to see whether we can go for deleteMany or not. In the production kind of environment, deletion is of high cost, we cannot revoke it and hence should be very careful in doing that.

Syntax:

db.collection.bulkWrite([{deleteMany : 
{“filter”: <document>,
“collation”:<document>
}
}])

Example:

try {
db.students.bulkWrite([
{ deleteMany : { "filter" : { "studentAge" : 20} } }
]);
} catch (e) {
print(e);
}

 Here, “deleteMany” will delete those documents that match the given filter(i.e,”studentAge” : 20)

MongoDB bulkWrite() Method Examples

Let’s look at some examples of bulkWrite method in MongoDB.

In the following examples, we are working with:

Database: studentsdb

Collection: students

Document: four documents that contain the details of the students.

Unordered Bulkwrite Example:

Here, the bulkWrite method executes multiple unordered operations because the value of the ordered parameter is set to false.

try {
db.students.bulkWrite([
{insertOne:{"document":{studentId:5, studentName:"GeekE", studentAge:24}}},
{ updateOne : {
"filter" : { "studentId" : 2 },
"update" : { $set : { "studentName" : "GeekyBest" } }
} },
{ deleteMany : { "filter" : { "studentAge" : 20} } },
{ replaceOne : {
"filter" : { "studentId" : 3 },
"replacement" : { "studentId" : 30, "studentName" : "BestGeek" }
} }
],{ ordered : false });
} catch (e) {
print(e);
}

Ordered BulkWrite Example:

If the value of the ordered parameter is set to true, then starting from insertOne, all the operations are executed one by one. BulkWrite will start execution from insertOne, updateOne, updateMany, replaceOne, deleteOne and finally deleteMany. 

The default option for “ordered” is “true”. But if it is set to “false” on a need basis, the results may vary from time to time.

try {
db.students.bulkWrite([
{insertOne:{"document":{studentId:5, studentName:"GeekE", studentAge:24}}},
{ updateOne : {
"filter" : { "studentId" : 2 },
"update" : { $set : { "studentName" : "GeekyBest" } }
} },
{ deleteMany : { "filter" : { "studentAge" : 20} } },
{ replaceOne : {
"filter" : { "studentId" : 3 },
"replacement" : { "studentId" : 40, "studentName" : "Geek11" }
} }
],{ ordered : true });
} catch (e) {
print(e);
}

Conclusion

In this article, we have covered the bulkWrite method in MongoDB. The bulkWrite method is used to perform multiple write operations and control the order of these operations.

In this article, we have covered the different operations in bulkWrite method with examples like insertOne & insertMany, deleteOne & deleteMany, replaceOne & replaceMany, etc. We also covered how to use ordered bulkWrite operations and unordered bulkWrite operations in MongoDB.


Article Tags :