Bulk Operations
On this page
Overview
In this guide, you can learn how to use the Node.js driver to perform bulk operations.
Bulk operations perform multiple write operations against one or more
collections within a database. In MongoDB, you refer to a collection by combining
the database name and the collection name in the format <database>.<collection>
.
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.
This guide includes the following sections:
Sample data presents the sample data that is used by the bulk operation examples.
Bulk Operation Types describes how to use different bulk operation types to perform bulk insert, replace, update, and delete operations.
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
To perform bulk write operations, ensure that your application meets the following requirements:
You are connected to MongoDB Server version 3.2 or later.
You are using Node.js driver version 3.6 or later.
Sample data
The examples in this guide use the following sample documents, which are stored
in the movies
collection in the sample_mflix
database:
// const movies = database.collection('movies'); const docs = [ { title: "Inception", year: 2010, rated: "PG-13", released: "2010-07-16" }, { title: "Interstellar", year: 2014, rated: "PG-13", released: "2014-11-07" }, { title: "The Dark Knight", year: 2008, rated: "PG-13", released: "2008-07-18" }, { title: "Tenet", year: 2020, rated: "PG-13", released: "2020-09-03"} ];
Bulk Operation Types
Insert
To perform a bulk insert operation, create a bulk operation object for each document
you want to insert. Then, pass a list of these operations to the bulkWrite()
method.
The following table describes the fields of the bulk operation object for an insert operation:
Field | Description |
---|---|
| This represents an insert operation. Type: Operation |
| The document to insert. Type: Document |
Insert Documents Example
This example performs the following actions:
Specifies four
InsertOneModel
instances in an array. EachInsertOneModel
represents a document to be inserted into themovies
collection within thedb
databse.Passes the array of models to the
bulkWrite()
method.Prints the number of inserted documents.
const bulkOps = [ { insertOne: { document: { title: "Inception", year: 2010, rated: "PG-13", released: "2010-07-16" } } }, { insertOne: { document: { title: "Interstellar", year: 2014, rated: "PG-13", released: "2014-11-07" } } }, { insertOne: { document: { title: "The Dark Knight", year: 2008, rated: "PG-13", released: "2008-07-18" } } }, { insertOne: { document: { title: "Tenet", year: 2020, rated: "PG-13", released: "2020-09-03" } } } ]; await movies.bulkWrite(bulkOps);
Inserted documents: 4
Replace
To perform a bulk replace operation, create a ReplaceOneModel
object for
each document you want to replace. Then, pass a list of models to the bulkWrite()
method.
The following table describes ReplaceOneModel
fields that you can set by calling
their corresponding builder methods:
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 |
Replace Documents 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.Passes the array of models to the
bulkWrite()
method.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 replace_result = await movies.bulkWrite(replaceOperations);
Modified documents: 2
Update
To perform a bulk update operation, create an UpdateOneModel
or UpdateManyModel
instance for each update you want to make. Then, pass an array of these models to the
bulkWrite()
method. 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 for UpdateOneModel
and
UpdateManyModel
fields that you can set:
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 |
Update Documents 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.Passes the array of models to the
bulkWrite()
method.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 update_result = await movies.bulkWrite(updateOperations); console.log(`Matched documents: ${result3.matchedCount}`); console.log(`Modified documents: ${result3.modifiedCount}`);
Modified documents: 2
Delete
To perform a bulk delete operation, create a DeleteOneModel
or DeleteManyModel
instance for each delete operation. Then, pass an array of these models to the
bulkWrite()
method. 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 for DeleteOneModel
and
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 |
Delete Documents Example
This example performs the following actions:
Specifies a
DeleteOneModel
and aDeleteManyModel
instance in an array. These models contain instructions to delete documents representing movies in themovies
collection.Passes the array of models to the
bulkWrite()
method.Prints the number of deleted documents.
const deleteOperations = [ { deleteOne: { filter: { title: "Dunkirk" } } }, { deleteMany: { filter: { rated: "R" } } } ]; const delete_result = await movies.bulkWrite(deleteOperations); console.log(`Deleted documents: ${result4.deletedCount}`);
Deleted documents: 2
Return Type
The bulkWrite()
method returns a BulkWriteResult
object, which provides
information about your bulk operation.
The BulkWriteResult
object has the following fields:
insertedCount
: the number of inserted documentsmatchedCount
: the number of matched documentsmodifiedCount
: the number of updated documentsupsertedCount
: the number of upserted documentsdeletedCount
: the number of deleted documents
Handling Exceptions
If any of the operations in a bulk write operation fail, 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.
A MongoBulkWriteError
object contains the following properties:
Property | Description |
---|---|
| The error message. Type: String |
| An array of errors that occured during the bulk write operation. Type: BulkWriteError[] |
| Write concern errors that occured 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 |
Additional Information
To learn more about bulk operations, see Bulk Write Operations in the Server manual.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: