Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js

Perform Bulk Operations

Note

If you specify a callback method, bulkWrite() returns nothing. If you do not specify one, this method returns a Promise that resolves to the result object when it completes. See our guide on Promises and Callbacks for more information, or the API documentation for information on the result object.

The bulkWrite() method performs batch write operations against a single collection. This method reduces the number of network round trips from your application to the server which therefore increases the throughput and performance. Bulk writes return a collection of results for all operations only after all operations passed to the method complete.

You can specify one or more of the following write operations in bulkWrite():

  • insertOne

  • updateOne

  • updateMany

  • deleteOne

  • deleteMany

  • replaceOne

The bulkWrite() method accepts the following parameters:

  • operations: specifies the bulk write operations to perform. Pass each operation to bulkWrite() as an object in an array. For examples that show the syntax for each write operation, see the bulkWrite API documentation.

  • options: optional settings that affect the execution of the operation, such as whether the write operations should execute in sequential order and the write concern.

    By default, MongoDB executes bulk write operations one-by-one in the specified order (i.e. serially). During an ordered bulk write, if an error occurs during the processing of an operation, MongoDB returns without processing the remaining operations in the list. In contrast, when ordered is false, MongoDB continues to process remaining write operations in the list. Unordered operations are theoretically faster since MongoDB can execute them in parallel, but should only be used if the writes do not depend on order.

If you create an index with a unique index constraint, you might encounter a duplicate key write error during an operation in the following format:

Error during bulkWrite, BulkWriteError: E11000 duplicate key error collection: ...

Similarly, if you attempt to perform a bulk write against a collection that uses schema validation, you may encounter warnings or errors related to the formatting of inserted or modified documents.

The following code sample performs a bulk write operation on the theaters collection in the sample_mflix database. The example call to bulkWrite() includes examples of insertOne, updateMany, and deleteOne write operations:

Note

This example connects to an instance of MongoDB and uses a sample data database. To learn more about connecting to your MongoDB instance and loading this database, see the Usage Examples guide.

const { MongoClient } = require("mongodb");
// Replace the uri string with your MongoDB deployment's connection string.
const uri =
"mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function run() {
try {
await client.connect();
const database = client.db("sample_mflix");
const theaters = database.collection("theaters");
const result = await theaters.bulkWrite([
{ insertOne:
{
"document": {
location: {
address: { street1: '3 Main St.', city: 'Anchorage', state: 'AK', zipcode: '99501' },
}
}
}
},
{ insertOne:
{
"document": {
location: {
address: { street1: '75 Penn Plaza', city: 'New York', state: 'NY', zipcode: '10001' },
}
}
}
},
{ updateMany:
{
"filter": { "location.address.zipcode" : "44011" },
"update": { $set : { "street2" : "25th Floor" } },
"upsert": true
}
},
{ deleteOne :
{ "filter" : { "location.address.street1" : "221b Baker St"} }
},
]);
console.log(result);
} finally {
await client.close();
}
}
run().catch(console.dir);

When you run the code sample, your output should resemble the following:

BulkWriteResult {
result: {
ok: 1,
writeErrors: [],
writeConcernErrors: [],
insertedIds: [ [Object], [Object] ],
nInserted: 2,
nUpserted: 0,
nMatched: 1,
nModified: 1,
nRemoved: 0,
upserted: [],
lastOp: { ts: [Timestamp], t: 17 }
},
insertedCount: 2,
matchedCount: 1,
modifiedCount: 1,
deletedCount: 0,
upsertedCount: 0,
upsertedIds: {},
insertedIds: { '0': 5ec4..., '1': 5ec4... },
n: 2
}
←  Watch for ChangesFundamentals →