Docs Menu
Docs Home
/ / /
Node.js Driver
/ / /

Bulk Operations

On this page

  • Overview
  • Sample data
  • Bulk Operation Types
  • Insert
  • Replace
  • Update
  • Delete
  • Return Type
  • Handling Exceptions
  • Additional Information
  • API Documentation

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.

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"}
];

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

insertOne

This represents an insert operation.
Type: Operation

document

The document to insert.
Type: Document

This example performs the following actions:

  • Specifies four InsertOneModel instances in an array. Each InsertOneModel represents a document to be inserted into the movies collection within the db 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

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

filter

The filter that matches the document you want to replace.
Type: Document

replacement

The replacement document.
Type: Document

collation

(Optional) The collation to use when sorting results. To learn more about collations, see the Collations guide.
Type: String or Object

hint

(Optional) The index to use for the operation. To learn more about indexes, see the Indexes guide.
Type: Bson

upsert

(Optional) Whether a new document is created if no document matches the filter.
By default, this field is set to false.
Type: Boolean

This example performs the following actions:

  • Specifies two ReplaceOneModel instances in an array. The ReplaceOneModel instances contain instructions to replace documents representing movies in the movies 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

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

filter

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

update

The update to perform.
Type: Document

arrayFilters

(Optional) A set of filters specifying which array elements an update applies to if you are updating an array-valued field.
Type: Array

collation

(Optional) The collation to use when sorting results. To learn more about collations, see the Collations guide.
Type: Object

hint

(Optional) The index to use for the operation. To learn more about indexes, see the Indexes guide.
Type: String or Object

upsert

(Optional) Whether a new document is created if no document matches the filter. By default, this field is set to false.
Type: Boolean

This example performs the following actions:

  • Specifies an UpdateOneModel and an UpdateManyModel instance in an array. These models contain instructions to update documents representing movies in the movies 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

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

filter

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

collation

(Optional) The collation to use when sorting results. To learn more about collations, see the Collations guide.
Type: Object

hint

(Optional) The index to use for the operation. To learn more about indexes, see the Indexes guide.
Type: String or Object

This example performs the following actions:

  • Specifies a DeleteOneModel and a DeleteManyModel instance in an array. These models contain instructions to delete documents representing movies in the movies 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

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 documents

  • matchedCount: the number of matched documents

  • modifiedCount: the number of updated documents

  • upsertedCount: the number of upserted documents

  • deletedCount: the number of deleted documents

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

message

The error message.
Type: String

writeErrors

An array of errors that occured during the bulk write operation.
Type: BulkWriteError[]

writeConcernErrors

Write concern errors that occured during execution of the bulk write operation.
Type: WriteConnectionError[]

result

The results of any successful operations performed before the exception was thrown.
Type: BulkWriteResult[]

err

The underlying error object, which may contain more details.
Type: Error

To learn more about bulk operations, see Bulk Write Operations in the Server manual.

To learn more about any of the methods or types discussed in this guide, see the following API documentation:

Back

Upsert