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" : "w3wikibest" } }
} }
]);
} 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

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:

  • db.collection.bulkWrite() method can be used in multi-document transactions.
  • If this method encounters an error in the transaction, then it will throw a BulkWriteException.
  • By default, this method executes operations in order.

Similar Reads

Syntax

db.collection.bulkWrite([ , , ..., ],{     writeConcern : ,     ordered : })...

MongoDB bulkWrite() Method Operations

Now let us understand the write operations:...

MongoDB bulkWrite() Method Examples

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

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....

Contact Us