db.collection.save()

On this page本页内容

Definition定义

db.collection.save()

mongo Shell Method

This page documents the mongo shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. 本页记录了mongo shell方法,未提及MongoDB Node.js驱动程序(或任何其他驱动程序)方法。For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.有关相应的MongoDB驱动程序API,请参阅特定的MongoDB驱动程序文档。

Updates an existing document or inserts a new document, depending on its document parameter.根据document参数更新现有文档或插入新文档。

Note

Starting in MongoDB 4.2, the db.collection.save() method is deprecated. 从MongoDB 4.2开始,不推荐使用db.collection.save()方法。Use db.collection.insertOne() or db.collection.replaceOne() instead.请改用db.collection.insertOne()db.collection.replaceOne()

The save() method has the following form:save()方法的形式如下:

db.collection.save(
   <document>,
   {
     writeConcern: <document>
   }
)
Parameter参数Type类型Description描述
document document A document to save to the collection.要保存到集合的文档。
writeConcern document

Optional.可选。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 in a transaction. 如果在事务中运行,请不要显式设置操作的写入关注点。To use write concern with transactions, see Transactions and Write Concern.要将写关注点用于事务,请参阅事务和写关注点

The save() returns an object that contains the status of the operation.save()返回一个包含操作状态的对象。

Returns:返回:A WriteResult object that contains the status of the operation.包含操作状态的WriteResult对象。

Behavior行为

Write Concern写作关注

The save() method uses either the insert or the update command, which use the default write concern. save()方法使用insertupdate命令,后者使用默认的写入关注To specify a different write concern, include the write concern in the options parameter.要指定不同的写入关注点,请在options参数中包含写入关注点。

Insert插入

If the document does not contain an _id field, then the save() method calls the insert() method. 如果文档不包含_id字段,则save()方法调用insert()方法。During the operation, the mongo shell will create an ObjectId and assign it to the _id field.在操作过程中,mongo shell将创建一个ObjectId并将其分配给_id字段。

Note

Most MongoDB driver clients will include the _id field and generate an ObjectId before sending the insert operation to MongoDB; however, if the client sends a document without an _id field, the mongod will add the _id field and generate the ObjectId.大多数MongoDB驱动程序客户端将包括_id字段,并在向MongoDB发送插入操作之前生成ObjectId;但是,如果客户端发送的文档没有_id字段,mongod将添加_id字段并生成ObjectId

Update更新

If the document contains an _id field, then the save() method is equivalent to an update with the upsert option set to true and the query predicate on the _id field.如果文档包含一个_id字段,那么save()方法相当于更新,upsert选项设置为true,查询谓词位于_id字段上。

Transactions事务

db.collection.save() can be used inside multi-document transactions.可以在多文档事务中使用。

For feature compatibility version (fcv) "4.4" and greater, if you save a document to a non-existing collection in a transaction, the collection is implicitly created.对于功能兼容性版本(fcv)"4.4"及更高版本,如果将文档保存到事务中不存在的集合,则会隐式创建该集合。

Note

You cannot create new collections in cross-shard write transactions. 不能在跨碎片写入事务中创建新集合。For example, if you write to an existing collection in one shard and implicitly create a collection in a different shard, MongoDB cannot perform both operations in the same transaction.例如,如果在一个碎片中写入现有集合,并在另一个碎片中隐式创建集合,MongoDB无法在同一事务中执行这两个操作。

For fcv "4.2" or less, save() operations that would result in the creation of a new collection are not allowed in a transaction.对于fcv"4.2"或更低版本,事务中不允许执行导致创建新集合的save()操作。

Do not explicitly set the write concern for the operation if run in a transaction. 如果在事务中运行,请不要显式设置操作的写入关注点。To use write concern with transactions, see Transactions and Write Concern.要将写关注点用于事务,请参阅事务和写关注点

Important

In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transactions should not be a replacement for effective schema design. 在大多数情况下,与单文档写入相比,多文档事务会带来更大的性能成本,而多文档事务的可用性不应取代有效的模式设计。For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. 对于许多场景,非规范化数据模型(嵌入式文档和数组)将继续适合您的数据和用例。That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.也就是说,对于许多场景,适当地建模数据将最大限度地减少对多文档事务的需求。

For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和oplog大小限制),请参阅生产注意事项

Sharded Clusters碎片簇

Starting in MongoDB 4.2, the save() method cannot be used with sharded collections that are not sharded by _id, and attempting to do so will result in an error. 从MongoDB 4.2开始,save()方法不能用于未按_id切分的切分集合,尝试这样做将导致错误。Use the insertOne() or replaceOne() method instead.请改用insertOne()replaceOne()方法。

Examples示例

Save a New Document without Specifying an _id Field在不指定_id字段的情况下保存新文档

In the following example, save() method performs an insert since the document passed to the method does not contain the _id field:在以下示例中,save()方法执行插入操作,因为传递给该方法的文档不包含_id字段:

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

During the insert, the shell will create the _id field with a unique ObjectId value, as verified by the inserted document:在插入过程中,shell将使用唯一的ObjectId值创建_id字段,并通过插入的文档进行验证:

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

The ObjectId values are specific to the machine and time when the operation is run. ObjectId值特定于机器和运行操作的时间。As such, your values may differ from those in the example.例如,你的价值观可能与你的例子中的不同。

Save a New Document Specifying an _id Field保存指定_id字段的新文档

In the following example, save() performs an update with upsert:true since the document contains an _id field:在以下示例中,save()使用upsert:true执行更新,因为文档包含一个_id字段:

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

Because the _id field holds a value that does not exist in the collection, the update operation results in an insertion of the document. 由于_id字段包含集合中不存在的值,因此更新操作会导致插入文档。The results of these operations are identical to an update() method with the upsert option set to true.这些操作的结果与upsert选项设置为trueupdate()方法相同。

The operation results in the following new document in the products collection:该操作将在products集合中生成以下新文档:

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

Replace an Existing Document替换现有文档

The products collection contains the following document:products集合包含以下文档:

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

The save() method performs an update with upsert:true since the document contains an _id field:save()方法使用upsert:true执行更新,因为文档包含一个_id字段:

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 in the following document:由于_id字段包含集合中存在的值,因此该操作将执行更新以替换文档,并生成以下文档:

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

Override Default Write Concern覆盖默认写关注点

The following operation to a replica set specifies a write concern of "w: majority" with a wtimeout of 5000 milliseconds such that the method returns after the write propagates to a majority of the voting replica set members or the method times out after 5 seconds.以下对副本集的操作指定了一个写关注点"w: majority"wtimeout为5000毫秒,这样该方法在写入传播到大多数投票副本集成员后返回,或者该方法在5秒后超时。

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

WriteResult

The save() returns a WriteResult object that contains the status of the insert or update operation. save()返回一个WriteResult对象,该对象包含插入或更新操作的状态。See WriteResult for insert and WriteResult for update for details.有关详细信息,请参阅WriteResult以获取插入信息,以及WriteResult以获取更新信息