Docs HomeMongoDB Manual

$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:您可以为以下项指定upsert选项:

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

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

Behavior行为

Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. 从MongoDB 5.0开始,update运算符按照字典顺序处理具有基于字符串的名称的文档字段。Fields with numeric names are processed in numeric order. See Update Operators Behavior for details.具有数字名称的字段按数字顺序处理。有关详细信息,请参阅更新运算符行为

Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $setOnInsert with an empty operand expression ( { } ). 从MongoDB 5.0开始,当您使用带有空操作数表达式({})的更新运算符(如$setOnInsert)时,mongod不再引发错误。An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).空更新不会导致任何更改,也不会创建操作日志条目(这意味着该操作是无操作)。

Example实例

The products collection contains no documents.products集合不包含任何文档。

Insert a new document using db.collection.updateOne() the upsert: true parameter.使用db.collection.updateOne()upsert: true参数插入一个新文档。

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

MongoDB uses <query> to create a new document with _id: 1. $setOnInsert updates the document as specified.MongoDB使用<query>创建一个_id1的新文档。$setOnInsert根据指定更新文档。

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

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

When the upsert parameter is true db.collection.updateOne():upsert参数为true时,db.collection.updateOne()

  • creates a new document创建新文档
  • applies the $set operation应用$set操作
  • applies the $setOnInsert operation应用$set操作

If db.collection.updateOne() matches an existing document, MongoDB only applies the $set operation.如果db.collection.updateOne()与现有文档匹配,MongoDB只应用$set操作。