Navigation

collection.bulkWrite()

Definition

collection.bulkWrite()

Bulk insert/update/delete multiple documents in a single collection with one call. Within the bulkWrite() function, you can specify one or more of the following write operations:

  • insertOne
  • updateOne
  • updateMany
  • deleteOne
  • deleteMany
  • replaceOne

Note

The bulkWrite() function operates on a single collection.

Usage

Example

To call the collection.bulkWrite() action from a Function, get a collection handle with database.collection() then call the handle’s bulkWrite() function.

exports = async function(arg){
    const doc1 = { "name": "velvet elvis", "quantity": 20, "reviews": [] };
    const doc2 = { "name": "mock turtleneck",  "quantity": 30, "reviews": [] };

    var collection = context.services.get("mongodb-atlas")
        .db("store")
        .collection("purchases");

    return await collection.bulkWrite(
        [{ insertOne: doc1}, { insertOne: doc2}],
        {ordered:true});
};

Parameters

The collection.bulkWrite() action has the following form:

bulkWrite(operations, options)
Parameter Description
operations

An array of bulkWrite operations to perform. Examples of supported operations include the following:

{ insertOne: { document: { a: 1 } } }

{ updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }

{ updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }

{ deleteOne: { filter: {c:1} } }

{ deleteMany: { filter: {c:1} } }

{ replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}}
options

Optional. An object that specifies the optional settings. Valid options are:

Option Type Description
ordered boolean (default = true) Execute write operation in ordered or unordered fashion. By default, Atlas executes bulk write operations one at a time in the specified order (i.e. serially). During an ordered bulk write, if an error occurs during the processing of an operation, Atlas 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.
bypassDocumentValidation boolean (default = false) Allow the driver to bypass schema validation
session client session optional session to use for this operation

Return Value

The collection.bulkWrite() function returns a Promise.