OPTIONS

Write Operations Overview

A write operation is any operation that creates or modifies data in the MongoDB instance. In MongoDB, write operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.

There are three classes of write operations in MongoDB: insert, update, and delete. Insert operations add new documents to a collection. Update operations modify existing documents, and delete operations delete documents from a collection. No insert, update, or delete can affect more than one document atomically.

For the update and remove operations, you can specify criteria, or filters, that identify the documents to update or remove. These operations use the same query syntax to specify the criteria as read operations.

MongoDB allows applications to determine the acceptable level of acknowledgement required of write operations. See Write Concern for more information.

Insert

MongoDB provides the following methods for inserting documents into a collection:

insertOne

New in version 3.2.

db.collection.insertOne() inserts a single document

The following diagram highlights the components of the MongoDB insertOne() operation:

The components of a MongoDB insertOne operations.

The following diagram shows the same query in SQL:

The components of a SQL INSERT statement.

Example

The following operation inserts a new document into the users collection. The new document has three fields name, age, and status. Since the document does not specify an _id field, MongoDB adds the _id field and a generated value to the new document. See Insert Behavior.

db.users.insertOne(
   {
      name: "sue",
      age: 26,
      status: "pending"
   }
)

For more information and examples, see db.collection.insertOne().

insertMany

New in version 3.2.

db.collection.insertMany() inserts multiple documents

The following diagram highlights the components of the MongoDB insertMany() operation:

The components of a MongoDB insertMany operations.

The following diagram shows the same query in SQL:

The components of a SQL INSERT statement with multiple values/rows.

Example

The following operation inserts three new documents into the users collection. Each document has three fields name, age, and status. Since the documents do not specify an _id field, MongoDB adds the _id field and a generated value to each document. See Insert Behavior.

db.users.insertMany(
   [
      { name: "sue", age: 26, status: "pending" },
      { name: "bob", age: 25, status: "enrolled" },
      { name: "ann", age: 28, status: "enrolled" }
   ]
)

For more information and examples, see db.collection.insertMany().

insert

In MongoDB, the db.collection.insert() method adds new documents to a collection. It can take either a single document or an array of documents to insert.

The following diagram highlights the components of a MongoDB insert operation:

The components of a MongoDB insert operations.

The following diagram shows the same query in SQL:

The components of a SQL INSERT statement.

Example

The following operation inserts a new document into the users collection. The new document has three fields name, age, and status. Since the document does not specify an _id field, MongoDB adds the _id field and a generated value to the new document. See Insert Behavior.

db.users.insert(
   {
      name: "sue",
      age: 26,
      status: "A"
   }
)

For more information and examples, see db.collection.insert().

Insert Behavior

The _id field is required in every MongoDB document. The _id field is like the document’s primary key.

If you add a new document without the _id field, the client library or the mongod instance adds an _id field and populates the field with a unique ObjectId. If you pass in an _id value that already exists, an exception is thrown.

The _id field is uniquely indexed by default in every collection.

Other Methods to Add Documents

The updateOne(), updateMany(), and replaceOne() operations accept the upsert parameter. When upsert : true, if no document in the collection matches the filter, a new document is created based on the information passed to the operation. See Update Behavior with the upsert Option.

Update

MongoDB provides the following methods for updating documents in a collection:

updateOne

New in version 3.2.

db.collection.updateOne() updates a single document.

The following diagram highlights the components of the MongoDB updateOne() operation:

The components of a MongoDB updateOne operation.

The following diagram shows the same query in SQL:

The components of a SQL UPDATE statement with LIMIT 1.

Example

This update operation on the users collection sets the status field to reject for the first document that matches the filter of age less than 18. See Update Behavior.

db.users.updateOne(
   { age: { $lt: 18 } },
   { $set: { status: "reject" } }
)

For more information and examples, see db.collection.updateOne().

updateMany

New in version 3.2.

db.collection.updateMany() updates multiple documents.

The following diagram highlights the components of the MongoDB updateMany() operation:

The components of a MongoDB updateMany operation.

The following diagram shows the same query in SQL:

The components of a SQL UPDATE statement.

Example

This update operation on the users collection sets the status field to reject for all documents that match the filter of age less than 18. See Update Behavior.

db.users.updateMany(
   { age: { $lt: 18 } },
   { $set: { status: "reject" } }
)

For more information and examples, see db.collection.updateMany().

replaceOne

New in version 3.2.

db.collection.replaceOne() replaces a single document.

The following diagram highlights the components of the MongoDB replaceOne() operation:

The components of a MongoDB replaceOne operation.

The following diagram shows the same query in SQL:

The components of a SQL UPDATE statement with LIMIT 1 used to REPLACE.

Example

This replace operation on the users collection replaces the first document that matches the filter of name is sue with a new document. See Replace Behavior.

db.users.replaceOne(
   { name: "sue" },
   { name: "amy", age : 25, score: "enrolled" }
)

For more information and examples, see db.collection.replaceOne().

update

In MongoDB, the db.collection.update() method modifies existing documents in a collection. The db.collection.update() method can accept query criteria to determine which documents to update as well as an options document that affects its behavior, such as the multi option to update multiple documents.

Operations performed by an update are atomic within a single document. For example, you can safely use the $inc and $mul operators to modify frequently-changed fields in concurrent applications.

The following diagram highlights the components of a MongoDB update operation:

The components of a MongoDB update operation.

The following diagram shows the same query in SQL:

The components of a SQL UPDATE statement.

Example

db.users.update(
   { age: { $gt: 18 } },
   { $set: { status: "A" } },
   { multi: true }
)

This update operation on the users collection sets the status field to A for the documents that match the criteria of age greater than 18.

For more information, see db.collection.update() and update() Examples.

Update Behavior

updateOne() and updateMany() use Update Operators such as $set, $unset, or $rename to modify existing documents.

updateOne() will update the first document that is returned by the filter. db.collection.findOneAndUpdate() offers sorting of the filter results, allowing a degree of control over which document is updated.

By default, the db.collection.update() method updates a single document. However, with the multi option, update() can update all documents in a collection that match a query.

The db.collection.update() method either updates specific fields in the existing document or replaces the document. See db.collection.update() for details as well as examples.

When performing update operations that increase the document size beyond the allocated space for that document, the update operation relocates the document on disk.

MongoDB preserves the order of the document fields following write operations except for the following cases:

  • The _id field is always the first field in the document.
  • Updates that include renaming of field names may result in the reordering of fields in the document.

Changed in version 2.6: Starting in version 2.6, MongoDB actively attempts to preserve the field order in a document. Before version 2.6, MongoDB did not actively preserve the order of the fields in a document.

Replace Behavior

replaceOne() cannot use Update Operators in the replacement document. The replacement document must consist of only <field> : <value> assignments.

replaceOne() will replace the first document that matches the filter. db.collection.findOneAndReplace() offers sorting of the filter results, allowing a degree of control over which document is replaced.

You cannot replace the _id field.

Update Behavior with the upsert Option

If update(), updateOne(), updateMany(), or replaceOne() include upsert : true and no documents match the filter portion of the operation, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies the matching document or documents.

Delete

MongoDB provides the following methods for deleting documents from a collection:

deleteOne

New in version 3.2.

db.collection.deleteOne() deletes a single document.

The following diagram highlights the components of the MongoDB deleteOne() operation:

The components of a MongoDB deleteOne operation.

The following diagram shows the same query in SQL:

The components of a SQL DELETE statement with LIMIT 1.

Example

This delete operation on the users collection deletes the first document where name is sue. See Delete Behavior.

db.users.deleteOne(
   { status: "reject" }
)

For more information and examples, see db.collection.deleteOne().

deleteMany

New in version 3.2.

db.collection.deleteMany() deletes multiple documents.

The following diagram highlights the components of the MongoDB deleteMany() operation:

The components of a MongoDB deleteMany operation.

The following diagram shows the same query in SQL:

The components of a SQL DELETE statement.

Example

This delete operation on the users collection deletes all documents where status is reject. See Delete Behavior.

db.users.deleteMany(
   { status: "reject" }
)

For more information and examples, see db.collection.deleteMany().

remove

In MongoDB, the db.collection.remove() method deletes documents from a collection. The db.collection.remove() method accepts query criteria to determine which documents to remove as well as an options document that affects its behavior, such as the justOne option to remove only a single document.

The following diagram highlights the components of a MongoDB remove operation:

The components of a MongoDB remove operation.

The following diagram shows the same query in SQL:

The components of a SQL DELETE.

Example

db.users.remove(
   { status: "D" }
)

This delete operation on the users collection removes all documents that match the criteria of status equal to D.

For more information, see db.collection.remove() method and Remove Documents.

Delete Behavior

deleteOne() will delete the first document that matches the filter. db.collection.findOneAndDelete() offers sorting of the filter results, allowing a degree of control over which document is deleted.

Remove Behavior

By default, db.collection.remove() method removes all documents that match its query. If the optional justOne parameter is set to true, remove() will limit the delete operation to a single document.

Additional Methods

The db.collection.save() method can either update an existing document or insert a document if the document cannot be found by the _id field. See db.collection.save() for more information and examples.

Bulk Write

MongoDB provides the db.collection.bulkWrite() method for executing multiple write operations in a group. Each write operation is still atomic on the level of a single document.

Example

The following bulkWrite() inserts several documents, performs an update, and then deletes several documents.

db.collection.bulkWrite(
   [
      { insertOne : { "document" : { name : "sue", age : 26 } } },
      { insertOne : { "document" : { name : "joe", age : 24 } } },
      { insertOne : { "document" : { name : "ann", age : 25 } } },
      { insertOne : { "document" : { name : "bob", age : 27 } } },
      { updateMany: {
         "filter" : { age : { $gt : 25} },
         "update" : { $set : { "status" : "enrolled" } }
         }
      },
      { deleteMany : { "filter" : { "status" : { $exists : true } } } }
   ]
)