Perform Bulk Operations
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 tobulkWrite()
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 executes in sequential order and the write concern.By default, MongoDB executes bulk write operations one-by-one in the specified order (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
isfalse
, MongoDB continues to process remaining write operations in the list. Unordered operations are theoretically faster since MongoDB can execute them in parallel, but only use them 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.
Example
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
You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.
1 // Bulk write operation 2 3 // Import MongoClient from the MongoDB node driver package 4 const { MongoClient } = require("mongodb"); 5 6 // Replace the uri string with your MongoDB deployment's connection string 7 const uri = "<connection string uri>"; 8 9 const client = new MongoClient(uri); 10 11 async function run() { 12 try { 13 const database = client.db("sample_mflix"); 14 const theaters = database.collection("theaters"); 15 16 // Insert a new document into the "theaters" collection 17 const result = await theaters.bulkWrite([ 18 { 19 insertOne: { 20 document: { 21 location: { 22 address: { 23 street1: "3 Main St.", 24 city: "Anchorage", 25 state: "AK", 26 zipcode: "99501", 27 }, 28 }, 29 }, 30 }, 31 }, 32 { 33 insertOne: { 34 document: { 35 location: { 36 address: { 37 street1: "75 Penn Plaza", 38 city: "New York", 39 state: "NY", 40 zipcode: "10001", 41 }, 42 }, 43 }, 44 }, 45 }, 46 { 47 // Update documents that match the specified filter 48 updateMany: { 49 filter: { "location.address.zipcode": "44011" }, 50 update: { $set: { is_in_ohio: true } }, 51 upsert: true, 52 }, 53 }, 54 { 55 // Delete a document that matches the specified filter 56 deleteOne: { filter: { "location.address.street1": "221b Baker St" } }, 57 }, 58 ]); 59 // Log the result of the bulk write operation 60 console.log(result); 61 } finally { 62 // Close the database connection when the operations are completed or if an error occurs 63 await client.close(); 64 } 65 } 66 run().catch(console.dir);
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 interface Address { 9 street1: string; 10 city: string; 11 state: string; 12 zipcode: string; 13 } 14 15 interface Theater { 16 location: { address: Address }; 17 is_in_ohio?: boolean; 18 } 19 20 async function run() { 21 try { 22 const database = client.db("sample_mflix"); 23 const theaters = database.collection<Theater>("theaters"); 24 25 const result = await theaters.bulkWrite([ 26 { 27 insertOne: { 28 document: { 29 location: { 30 address: { 31 street1: "3 Main St.", 32 city: "Anchorage", 33 state: "AK", 34 zipcode: "99501", 35 }, 36 }, 37 }, 38 }, 39 }, 40 { 41 insertOne: { 42 document: { 43 location: { 44 address: { 45 street1: "75 Penn Plaza", 46 city: "New York", 47 state: "NY", 48 zipcode: "10001", 49 }, 50 }, 51 }, 52 }, 53 }, 54 { 55 updateMany: { 56 // Important: You lose type safety when you use dot notation in queries 57 filter: { "location.address.zipcode": "44011" }, 58 update: { $set: { is_in_ohio: true } }, 59 upsert: true, 60 }, 61 }, 62 { 63 deleteOne: { 64 filter: { "location.address.street1": "221b Baker St" }, 65 }, 66 }, 67 ]); 68 69 console.log(result); 70 } finally { 71 await client.close(); 72 } 73 } 74 run().catch(console.dir);
Running the preceding example results in the following output:
BulkWriteResult { insertedCount: 2, matchedCount: 1, modifiedCount: 1, deletedCount: 0, upsertedCount: 0, upsertedIds: {}, insertedIds: { '0': new ObjectId("..."), '1': new ObjectId("...") } }