Bulk Operations
On this page
- Overview
- Sample Data
- Bulk Insert Operations
- Collection Bulk Inserts
- Client Bulk Inserts
- Bulk Replace Operations
- Collection Bulk Replacements
- Client Bulk Replacements
- Bulk Update Operations
- Collection Bulk Updates
- Client Bulk Updates
- Bulk Delete Operations
- Collection Bulk Deletes
- Client Bulk Deletes
- Return Type
- BulkWriteResult
- ClientBulkWriteResult
- Handling Exceptions
- Collection Bulk Write Exceptions
- Client Bulk Write Exceptions
- Additional Information
- API Documentation
Overview
In this guide, you can learn how to use the Node.js driver to perform bulk operations. Bulk operations help reduce the number of calls to the server. Instead of sending a request for each operation, you can perform multiple operations within one action.
Tip
To learn more about bulk operations, see Bulk Write Operations in the MongoDB Server manual.
You can use bulk operations to perform multiple write operations on
a collection. You can also run bulk operations from the client,
which allows you to perform bulk writes across multiple namespaces.
In MongoDB, a namespace consists of the database name and the collection
name in the format <database>.<collection>
.
This guide includes the following sections:
Bulk Insert Operations describes how to perform bulk insert operations on your collection or client.
Bulk Replace Operations describes how to perform bulk replace operations on your collection or client.
Bulk Update Operations describes how to perform bulk update operations on your collection or client.
Bulk Delete Operations describes how to perform bulk delete operations on your collection or client.
Return Type describes the return object that results from your bulk write operations.
Handling Exceptions describes the exceptions that occur if any of the operations in a bulk write operation fail.
Additional Information provides links to resources and API documentation for types and methods mentioned in this guide.
Important
Server and Driver Version Requirements
Collection-level bulk write operations require the following versions:
MongoDB Server version 3.2 or later
Node.js driver version 3.6 or later
Client-level bulk write operations require the following versions:
MongoDB Server version 8.0 or later
Node.js driver version 6.10 or later
Sample Data
The examples in this guide use the movies
and users
collections in
the sample_mflix
database, which is included in the Atlas sample datasets.
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the
Get Started with Atlas guide.
Bulk Insert Operations
To perform a bulk insert operation, create a bulk operation model for each document
you want to insert. Then, pass a list of these models to the bulkWrite()
method.
This section describes how to perform the following types of bulk operations:
Collection Bulk Inserts
To perform a bulk insert operation on your collection, create an InsertOneModel
for each operation. Then, call the bulkWrite()
method on your collection
and pass an array of models as a parameter. To create an InsertOneModel
,
specify the model's document
field and set it to the document you want to insert.
Example
This example performs the following actions:
Specifies two
InsertOneModel
instances in an array. EachInsertOneModel
represents a document to insert into themovies
collection in thesample_mflix
database.Calls the
bulkWrite()
method on themovies
collection and passes an array of models as a parameter.Prints the number of inserted documents.
const insertModels = [{ insertOne: { document: { title: "The Favourite", year: 2018, rated: "R", released: "2018-12-21" } } }, { insertOne: { document: { title: "I, Tonya", year: 2017, rated: "R", released: "2017-12-08" } } }]; const insertResult = await movies.bulkWrite(insertModels); console.log(`Inserted documents: ${insertResult.insertedCount}`);
Inserted documents: 2
Client Bulk Inserts
To perform a bulk insert operation across multiple collections or
databases, create a ClientBulkWriteModel
for each operation. Then,
call the bulkWrite()
method on your client and pass an array of
models as a parameter.
The following table describes the fields that you can set in a
ClientBulkWriteModel
to specify an insert operation:
Field | Description |
---|---|
| The namespace in which to insert a document. Type: String |
| The operation you want to perform. For insert operations,
set this field to "insertOne" .Type: String |
| The document to insert. Type: Document |
Example
This example performs the following actions:
Specifies three
ClientBulkWriteModel
instances in an array. The first two models represent documents to insert into themovies
collection, and the last model represents a document to insert into theusers
collection.Calls the
bulkWrite()
method on a client and passes an array of models as a parameter.Prints the number of inserted documents.
const clientInserts = [{ namespace: "sample_mflix.movies", name: "insertOne", document: { title: "The Favourite", year: 2018, rated: "R", released: "2018-12-21" } }, { namespace: "sample_mflix.movies", name: "insertOne", document: { title: "I, Tonya", year: 2017, rated: "R", released: "2017-12-08" } }, { namespace: "sample_mflix.users", name: "insertOne", document: { name: "Brian Schwartz", email: "bschwartz@example.com" } }]; const clientInsertRes = await client.bulkWrite(clientInserts); console.log(`Inserted documents: ${clientInsertRes.insertedCount}`);
Inserted documents: 3
Bulk Replace Operations
To perform a bulk replace operation, create a bulk operation model for each document
you want to replace. Then, pass a list of these models to the bulkWrite()
method.
This section describes how to perform the following types of bulk operations:
Collection Bulk Replacements
To perform a bulk replace operation on your collection, create a ReplaceOneModel
for each operation. Then, call the bulkWrite()
method on your collection
and pass an array of models as a parameter.
The following table describes the fields that you can set in a
ReplaceOneModel
:
Field | Description |
---|---|
| The filter that matches the document you want to replace. Type: Document |
| The replacement document. Type: Document |
| (Optional) The collation to use when sorting results. To learn more
about collations, see the Collations guide. Type: String or Object |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes guide. Type: Bson |
| (Optional) Whether a new document is created if no document matches the filter. By default, this field is set to false .Type: Boolean |
Example
This example performs the following actions:
Specifies two
ReplaceOneModel
instances in an array. TheReplaceOneModel
instances contain instructions to replace documents representing movies in themovies
collection.Calls the
bulkWrite()
method on themovies
collection and passes an array of models as a parameter.Prints the number of modified documents.
const replaceOperations = [{ replaceOne: { filter: { title: "The Dark Knight" }, replacement: { title: "The Dark Knight Rises", year: 2012, rating: "PG-13" }, upsert: false } }, { replaceOne: { filter: { title: "Inception" }, replacement: { title: "Inception Reloaded", year: 2010, rating: "PG-13" }, upsert: false } }]; const replaceResult = await movies.bulkWrite(replaceOperations); console.log(`Modified documents: ${replaceResult.modifiedCount}`);
Modified documents: 2
Client Bulk Replacements
To perform a bulk replace operation across multiple collections or
databases, create a ClientBulkWriteModel
for each operation. Then,
call the bulkWrite()
method on your client and pass an array of
models as a parameter.
The following table describes the fields that you can set in a
ClientBulkWriteModel
to specify a replace operation:
Field | Description |
---|---|
| The namespace in which to replace a document. Type: String |
| The operation you want to perform. For replace operations,
set this field to "replaceOne" .Type: String |
| The filter that matches the document you want to replace. Type: Document |
| The replacement document. Type: Document |
| (Optional) The collation to use when sorting results. To learn more
about collations, see the Collations guide. Type: String or Object |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes guide. Type: Bson |
Example
This example performs the following actions:
Specifies three
ClientBulkWriteModel
instances in an array. The first two models contain replacement instructions for documents in themovies
collection, and the last model contains replacement instructions for a document in theusers
collection.Calls the
bulkWrite()
method on a client and passes an array of models as a parameter.Prints the number of modified documents.
const clientReplacements = [{ namespace: "sample_mflix.movies", name: "replaceOne", filter: { title: "The Dark Knight" }, replacement: { title: "The Dark Knight Rises", year: 2012, rating: "PG-13" } }, { namespace: "sample_mflix.movies", name: "replaceOne", filter: { title: "Inception" }, replacement: { title: "Inception Reloaded", year: 2010, rating: "PG-13" } }, { namespace: "sample_mflix.users", name: "replaceOne", filter: { name: "April Cole" }, replacement: { name: "April Franklin", email: "aprilfrank@example.com" } }]; const clientReplaceRes = await client.bulkWrite(clientReplacements); console.log(`Modified documents: ${clientReplaceRes.modifiedCount}`);
Modified documents: 3
Bulk Update Operations
To perform a bulk update operation, create a bulk operation model for each update
you want to make. Then, pass a list of these models to the bulkWrite()
method.
This section describes how to perform the following types of bulk operations:
Collection Bulk Updates
To perform a bulk update operation on your collection, create an UpdateOneModel
or UpdateManyModel
for each operation. Then, call the bulkWrite()
method on
your collection and pass an array of models as a parameter. An UpdateOneModel
updates only one document that matches a filter, while an UpdateManyModel
updates
all documents that match a filter.
The following table describes the fields you can set in an UpdateOneModel
or
UpdateManyModel
:
Field | Description |
---|---|
| The filter that matches one or more documents you want to update. When
specified in an UpdateOneModel , only the first matching document will
be updated. When specified in an UpdateManyModel , all matching documents
will be updated.Type: Document |
| The update to perform. Type: Document |
| (Optional) A set of filters specifying which array elements an update
applies to if you are updating an array-valued field. Type: Array |
| (Optional) The collation to use when sorting results. To learn more about
collations, see the Collations guide. Type: Object |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes guide. Type: String or Object |
| (Optional) Whether a new document is created if no document matches the filter.
By default, this field is set to false .Type: Boolean |
Example
This example performs the following actions:
Specifies an
UpdateOneModel
and anUpdateManyModel
instance in an array. These models contain instructions to update documents representing movies in themovies
collection.Calls the
bulkWrite()
method on themovies
collection and passes an array of models as a parameter.Prints the number of modified documents.
const updateOperations = [{ updateOne: { filter: { title: "Interstellar" }, update: { $set: { title: "Interstellar Updated", genre: "Sci-Fi Adventure" } }, upsert: true } }, { updateMany: { filter: { rated: "PG-13" }, update: { $set: { rated: "PG-13 Updated", genre: "Updated Genre" } } } }]; const updateResult = await movies.bulkWrite(updateOperations); console.log(`Modified documents: ${updateResult.modifiedCount}`);
Modified documents: 2320
Client Bulk Updates
To perform a bulk update operation across multiple collections or
databases, create a ClientBulkWriteModel
for each operation. Then,
call the bulkWrite()
method on your client and pass an array of
models as a parameter.
The following table describes the fields you can set in a ClientBulkWriteModel
to specify an update operation:
Field | Description |
---|---|
| The namespace in which to update a document. Type: String |
| The operation you want to perform. For update operations,
set this field to "updateOne" or "updateMany" .Type: String |
| The filter that matches one or more documents you want to update. If
you set the model name to "updateOne" , only the first matching
document is updated. If you set name to "updateMany" , all
matching documents are updated.Type: Document |
| The updates to perform. Type: Document or Document[] |
| (Optional) A set of filters specifying which array elements an update
applies to if you are updating an array-valued field. Type: Document[] |
| (Optional) The collation to use when sorting results. To learn more about
collations, see the Collations guide. Type: Document |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes guide. Type: Document or String |
| (Optional) Whether a new document is created if no document matches the filter.
By default, this field is set to false .Type: Boolean |
Example
This example performs the following actions:
Specifies two
ClientBulkWriteModel
instances in an array. The first model specifies an update many operation on themovies
collection, and the second model specifies an update one operation on theusers
collection.Calls the
bulkWrite()
method on a client and passes an array of models as a parameter.Prints the number of modified documents.
const clientUpdates = [{ namespace: "sample_mflix.movies", name: "updateMany", filter: { rated: "PG-13" }, update: { $set: { rated: "PG-13 Updated", genre: "Updated Genre" } }, upsert: false }, { namespace: "sample_mflix.users", name: "updateOne", filter: { name: "Jon Snow" }, update: { $set: { name: "Aegon Targaryen", email: "targaryen@example.com" } }, upsert: false }]; const clientUpdateRes = await client.bulkWrite(clientUpdates); console.log(`Modified documents: ${clientUpdateRes.modifiedCount}`);
Modified documents: 2320
Bulk Delete Operations
To perform a bulk delete operation, create a bulk operation model for each delete
operation. Then, pass a list of these models to the bulkWrite()
method.
This section describes how to perform the following types of bulk operations:
Collection Bulk Deletes
To perform a bulk delete operation on your collection, create a DeleteOneModel
or DeleteManyModel
for each operation. Then, call the bulkWrite()
method on
your collection and pass an array of models as a parameter. A DeleteOneModel
deletes only one document that matches a filter, while a DeleteManyModel
deletes
all documents that match a filter.
The following table describes the fields you can set in a DeleteOneModel
or
DeleteManyModel
:
Field | Description |
---|---|
| The filter that matches one or more documents you want to delete. When
specified in a DeleteOneModel , only the first matching document will
be deleted. When specified in a DeleteManyModel , all matching documents
will be deleted.Type: Document |
| (Optional) The collation to use when sorting results. To learn more about
collations, see the Collations guide. Type: Object |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes guide. Type: String or Object |
Example
This example performs the following actions:
Specifies a
DeleteOneModel
and aDeleteManyModel
instance in an array. These models contain instructions to delete documents in themovies
collection.Calls the
bulkWrite()
method on themovies
collection and passes an array of models as a parameter.Prints the number of deleted documents.
const deleteOperations = [{ deleteOne: { filter: { title: "Dunkirk" } } }, { deleteMany: { filter: { rated: "R" } } }]; const deleteResult = await movies.bulkWrite(deleteOperations); console.log(`Deleted documents: ${deleteResult.deletedCount}`);
Deleted documents: 5538
Client Bulk Deletes
To perform a bulk delete operation across multiple collections or
databases, create a ClientBulkWriteModel
for each operation. Then,
call the bulkWrite()
method on your client and pass an array of
models as a parameter.
The following table describes the fields you can set in a ClientBulkWriteModel
to specify a delete operation:
Field | Description |
---|---|
| The namespace in which to delete a document. Type: String |
| The operation you want to perform. For delete operations,
set this field to "deleteOne" or "deleteMany" .Type: String |
| The filter that matches one or more documents you want to delete. If
you set the model name to "deleteOne" , only the first matching
document is deleted. If you set name to "deleteMany" , all
matching documents are deleted.Type: Document |
| (Optional) The index to use for the operation. To learn more about
indexes, see the Indexes guide. Type: Document or String |
| (Optional) The collation to use when sorting results. To learn more about
collations, see the Collations guide. Type: Document |
Example
This example performs the following actions:
Specifies two
ClientBulkWriteModel
instances in an array. The first model specifies a delete many operation on themovies
collection, and the second model specifies a delete one operation on theusers
collection.Calls the
bulkWrite()
method on a client and passes an array of models as a parameter.Prints the number of modified documents.
const clientDeletes = [{ namespace: "sample_mflix.movies", name: "deleteMany", filter: { rated: "R" } }, { namespace: "sample_mflix.users", name: "deleteOne", filter: { email: "emilia_clarke@gameofthron.es" } }]; const clientDeleteRes = await client.bulkWrite(clientDeletes); console.log(`Deleted documents: ${clientDeleteRes.deletedCount}`);
Deleted documents: 5538
Return Type
BulkWriteResult
The Collection.bulkWrite()
method returns a BulkWriteResult
object, which provides
information about your bulk operation.
The following tables describes the fields of a BulkWriteResult
object:
Field | Description |
---|---|
| The number of inserted documents |
| The number of matched documents |
| The number of updated documents |
| The number of upserted documents |
| The number of deleted documents |
ClientBulkWriteResult
The MongoClient.bulkWrite()
method returns a ClientBulkWriteResult
object,
which includes information about the client bulk write operation.
The following tables describes the fields of a ClientBulkWriteResult
object:
Field | Description |
---|---|
| A boolean value indicating whether the bulk write was acknowledged |
| The number of inserted documents |
| The number of matched documents |
| The number of updated documents |
| The number of upserted documents |
| The number of deleted documents |
| The results of each individual successful insert operation |
| The results of each individual successful update operation |
| The results of each individual successful delete operation |
Handling Exceptions
Collection Bulk Write Exceptions
If any bulk write operations called on a collection are unsuccessful,
the Node.js driver throws a MongoBulkWriteError
and does not perform any further operations if the
ordered
option is set to true
. If ordered
is set to false
, it will
attempt to continue with subsequent operations.
Tip
To learn more about ordered and unordered bulk operations, see the Ordered vs Unordered Operations section in the Bulk Write guide from the MongoDB Server manual.
A MongoBulkWriteError
object contains the following properties:
Property | Description |
---|---|
| The error message. Type: String |
| An array of errors that occurred during the bulk write operation. Type: BulkWriteError[] |
| Write concern errors that occurred during execution of the bulk write operation. Type: WriteConnectionError[] |
| The results of any successful operations performed before the exception was
thrown. Type: BulkWriteResult[] |
| The underlying error object, which may contain more details. Type: Error |
Client Bulk Write Exceptions
If any bulk write operations called on your client are unsuccessful, the Node.js driver
generates a MongoClientBulkWriteError
. By default, the driver does
not perform any subsequent operations after encountering an error. If you
pass the ordered
option to the bulkWrite()
method and set it to false
,
the driver continues to attempt the remaining operations.
A MongoClientBulkWriteError
object contains the following properties:
Property | Description |
---|---|
| An array of documents specifying each write concern error. Type: Document[] |
| An map of errors that occurred during individual write operations. Type: Map<number, ClientBulkWriteError> |
| The partial result of the client bulk write that reflects the operation's
progress before the error. Type: ClientBulkWriteResult |
Additional Information
To learn more about bulk operations, see Bulk Write Operations in the MongoDB Server manual.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: