db.collection.initializeOrderedBulkOp()

Tip

Starting in version 3.2, MongoDB also provides thedb.collection.bulkWrite() method for performing bulkwrite operations.

Definition

  • db.collection.initializeOrderedBulkOp()

mongo Shell Method

This page documents the mongo shell method, and doesnot refer to the MongoDB Node.js driver (or any other driver)method. For corresponding MongoDB driver API, refer to your specificMongoDB driver documentation instead.

Initializes and returns a new Bulk() operations builderfor a collection. The builder constructs an ordered list of writeoperations that MongoDB executes in bulk.

Returns:new Bulk() operations builder object.

Behavior

Order of Operation

With an ordered operations list, MongoDB executes the writeoperations in the list serially.

Execution of Operations

When executing an ordered list of operations, MongoDBgroups the operations by the operation type andcontiguity; i.e. contiguous operations of the same type are groupedtogether. For example, if an ordered list has two insert operationsfollowed by an update operation followed by another insert operation,MongoDB groups the operations into three separate groups: first groupcontains the two insert operations, second group contains the updateoperation, and the third group contains the last insert operation. Thisbehavior is subject to change in future versions.

Each group of operations can have at most 1000 operations. If a group exceeds this limit, MongoDB will divide the group intosmaller groups of 1000 or less. For example, if the bulk operations listconsists of 2000 insert operations, MongoDB creates 2 groups, each with1000 operations.

The sizes and grouping mechanics are internal performance details andare subject to change in future versions.

To see how the operations are grouped for a bulk operation execution,call Bulk.getOperations()after the execution.

Executing an ordered list of operations on asharded collection will generally be slower than executing anunordered listsince with an ordered list, each operation must wait for the previousoperation to finish.

Error Handling

If an error occurs during the processing of one of the writeoperations, MongoDB will return without processing any remaining writeoperations in the list.

Examples

The following initializes a Bulk() operations builder on theusers collection, adds a series of write operations, and executesthe operations:

  1. var bulk = db.users.initializeOrderedBulkOp();
  2. bulk.insert( { user: "abc123", status: "A", points: 0 } );
  3. bulk.insert( { user: "ijk123", status: "A", points: 0 } );
  4. bulk.insert( { user: "mop123", status: "P", points: 0 } );
  5. bulk.find( { status: "D" } ).remove();
  6. bulk.find( { status: "P" } ).update( { $set: { comment: "Pending" } } );
  7. bulk.execute();

See also