对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

$setOnInsert(更新操作符)

$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. If the update operation does not result in an insert, $setOnInsert does nothing.

您可以指定 upsert 选项用于:

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

要在嵌入式文档或数组中指定 <field>,请使用点符号。

从 MongoDB 5.0 开始,更新操作符按字典顺序处理具有基于字符串的名称的文档字段。具有数字名称的字段按数字顺序处理。详情请参阅更新操作符行为。

Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $setOnInsert with an empty operand expression ( { } ). An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).

products 集合不包含任何文档。

使用 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.

products 集合包含新插入的文档:

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

当 upsert 参数为 true db.collection.updateOne() 时:

如果db.collection.updateOne()与现有文档匹配,MongoDB 只应用$set操作。

给本页内容打分

在此页面上