bulkWrite() method
db.collection.bulkWrite()
method can perform these operations:
- insertOne
- updateOne
- updateMany
- replaceOne
- deleteOne
- deleteMany
It has the following syntax:
db.collection(
[
{
<operation1>: {
"<option1>": <document1>,
"<option2>": <document2>
}
},
{
<operation2>: {
"<option1>": <document1>,
"<option2>": <document2>
}
},
...
],
{
writeConcern: <document>,
ordered: <boolean>
}
)
bulkWrite()
method can be either ordered or unordered, meaning the array of operations can be executed in series or in parallel. By default, MongoDB performs bulkWrite()
in ordered mode.
For example:
db.customers.bulkWrite(
[
{
insertOne: {
"document": {
email: "[email protected]",
age: 210,
gender: "M"
}
}
},
{
insertOne: {
"document": {
email: "[email protected]",
age: 220,
gender: "F"
}
}
},
{
updateMany: {
"filter": {
age: {
$gt: 100
}
},
"update": {
$set: {
age: 10
}
}
}
},
{
replaceOne: {
"filter": {
email: "[email protected]"
},
"replacement": {
email: "[email protected]",
age: 10,
gender: "F"
}
}
},
{
deleteMany: {
"filter": {
age: {
$eq: 10
}
}
}
}
]
)
In this example:
- Add two documents
- Update all documents with age >= 200, and set their age to 10
- Replace a document matching email
[email protected]
with a new document - Remove all documents that has age equal to 10
Output:
{
acknowledged: true,
insertedCount: 2,
insertedIds: {
'0': ObjectId("60bcbeedd483412bb240775d"),
'1': ObjectId("60bcbeedd483412bb240775e")
},
matchedCount: 3,
modifiedCount: 3,
deletedCount: 2,
upsertedCount: 0,
upsertedIds: {}
}
We can also use aggregation pipelines inside the updateOne or updateMany operations:
db.customers.bulkWrite(
[
{
insertOne: {
"document": {
email: "[email protected]",
age: 210,
gender: "M"
}
}
},
{
updateMany: {
"filter": {
age: {
$gt: 200
}
},
"update": [
{
$set: {
age: 10
}
},
{
$project: {
email: 1,
age: 1
}
}
]
}
},
{
deleteMany: {
"filter": {
age: {
$eq: 10
}
}
}
}
]
)
Output:
{
acknowledged: true,
insertedCount: 1,
insertedIds: { '0': ObjectId("60bcc32ed483412bb2407767") },
matchedCount: 1,
modifiedCount: 1,
deletedCount: 1,
upsertedCount: 0,
upsertedIds: {}
}