$setOnInsert

On this page本页内容

Definition定义

$setOnInsert

If an update operation with upsert: true results in an insert of a document, then $setOnInsert assigns the specified values to the fields in the document. 如果upsert:true的更新操作导致插入文档,则$setOnInsert会将指定的值分配给文档中的字段。If the update operation does not result in an insert, $setOnInsert does nothing.如果更新操作没有导致插入,$setOnInsert不执行任何操作。

You can specify the upsert option for either the db.collection.update() or db.collection.findAndModify() methods.您可以为db.collection.update()方法和db.collection.findAndModify()方法指定upsert选项。

db.collection.update(
   <query>,
   { $setOnInsert: { <field1>: <value1>, ... } },
   { upsert: true }
)

To specify a <field> in an embedded document or in an array, use dot notation.若要在嵌入式文档或数组中指定一个<field>,请使用点表示法

Example示例

A collection named products contains no documents.名为products的集合不包含文档。

Then, the following db.collection.update() with upsert: true inserts a new document.然后,下面的db.collection.update()方法使用upsert:true插入新文档。

db.products.update(
  { _id: 1 },
  {
     $set: { item: "apple" },
     $setOnInsert: { defaultQty: 100 }
  },
  { upsert: true }
)

MongoDB creates a new document with _id equal to 1 from the <query> condition, and then applies the $set and $setOnInsert operations to this document.MongoDB根据<query>条件创建一个_id等于1的新文档,然后将$set$setOnInsert操作应用于该文档。

The products collection contains the newly-inserted document:products集合包含新插入的文档:

{ "_id" : 1, "item" : "apple", "defaultQty" : 100 }

If the db.collection.update() with upsert: true had found a matching document, then MongoDB performs an update, applying the $set operation but ignoring the $setOnInsert operation.如果db.collection.update()使用upsert:true已找到匹配的文档,然后MongoDB执行更新,应用$set操作,但忽略$setOnInsert操作。