db.collection.save()

Definition

  • db.collection.save()

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.

Updates an existing document or inserts anew document, depending on its document parameter.

Note

MongoDB deprecates the db.collection.save() method.Instead use db.collection.insertOne() ordb.collection.replaceOne() instead.

The save() method has the following form:

  1. db.collection.save(
  2. <document>,
  3. {
  4. writeConcern: <document>
  5. }
  6. )

ParameterTypeDescriptiondocumentdocumentA document to save to the collection.writeConcerndocumentOptional. A document expressing the write concern. Omit to use the default write concern.See Write Concern.

Do not explicitly set the write concern for the operation if run ina transaction. To use write concern with transactions, seeTransactions and Write Concern.

Changed in version 2.6: The save() returns an object thatcontains the status of the operation.

Returns:A WriteResult object that contains thestatus of the operation.

Behavior

Write Concern

Changed in version 2.6.

The save() method uses either theinsert or the update command, which use thedefault write concern. To specify adifferent write concern, include the write concern in the optionsparameter.

Insert

If the document does not contain an _id field, then thesave() method calls theinsert() method. During the operation, themongo shell will create an ObjectId andassign it to the _id field.

Note

Most MongoDB driver clients will include the _id field andgenerate an ObjectId before sending the insert operation toMongoDB; however, if the client sends a document without an _idfield, the mongod will add the _id field and generatethe ObjectId.

Update

If the document contains an _id field, then thesave() method is equivalent to an update withthe upsert option set to true and thequery predicate on the _id field.

Transactions

db.collection.save() can be used inside multi-document transactions.

If the operation results in an insert, the collection must alreadyexist.

Do not explicitly set the write concern for the operation if run ina transaction. To use write concern with transactions, seeTransactions and Write Concern.

Important

In most cases, multi-document transaction incurs a greaterperformance cost over single document writes, and theavailability of multi-document transactions should not be areplacement for effective schema design. For many scenarios, thedenormalized data model (embedded documents and arrays) will continue to be optimal for yourdata and use cases. That is, for many scenarios, modeling your dataappropriately will minimize the need for multi-documenttransactions.

For additional transactions usage considerations(such as runtime limit and oplog size limit), see alsoProduction Considerations.

Examples

Save a New Document without Specifying an _id Field

In the following example, save() methodperforms an insert since the document passed to the method does notcontain the _id field:

  1. db.products.save( { item: "book", qty: 40 } )

During the insert, the shell will create the _id field witha unique ObjectId value, as verified by the inserteddocument:

  1. { "_id" : ObjectId("50691737d386d8fadbd6b01d"), "item" : "book", "qty" : 40 }

The ObjectId values are specific to the machine and time when theoperation is run. As such, your values may differ from those in theexample.

Save a New Document Specifying an _id Field

In the following example, save() performs anupdate with upsert:true since the document contains an _id field:

  1. db.products.save( { _id: 100, item: "water", qty: 30 } )

Because the id field holds a value that _does not exist in thecollection, the update operation results in an insertion of thedocument. The results of these operations are identical to anupdate() method with the upsert option set totrue.

The operation results in the following new document in the productscollection:

  1. { "_id" : 100, "item" : "water", "qty" : 30 }

Replace an Existing Document

The products collection contains the following document:

  1. { "_id" : 100, "item" : "water", "qty" : 30 }

The save() method performs an update withupsert:true since the document contains an _id field:

  1. db.products.save( { _id : 100, item : "juice" } )

Because the _id field holds a value that exists in the collection,the operation performs an update to replace the document and results inthe following document:

  1. { "_id" : 100, "item" : "juice" }

Override Default Write Concern

The following operation to a replica set specifies a writeconcern of "w: majority" with awtimeout of 5000 milliseconds such that the method returns afterthe write propagates to a majority of the voting replica set members orthe method times out after 5 seconds.

Changed in version 3.0: In previous versions, majority referred to the majority of allmembers of the replica set instead of the majority of the votingmembers.

  1. db.products.save(
  2. { item: "envelopes", qty : 100, type: "Clasp" },
  3. { writeConcern: { w: "majority", wtimeout: 5000 } }
  4. )

WriteResult

Changed in version 2.6.

The save() returns a WriteResultobject that contains the status of the insert or update operation. SeeWriteResult for insert andWriteResult for update for details.