mongo的update $set和upsert: true有什么区别

发布于 2025-01-15 03:38:42 字数 115 浏览 1 评论 0原文

我想问这个问题并回答它,因为我正在浏览 updateMany() 和 UpdateOne() 的 mongo 文档,作为初学者,我最初对使用 $set 运算符和“upsert: true”之间的区别感到困惑“ 选项。

I wanted to ask this question and answer it because I was going through the mongo documentation for updateMany() and UpdateOne(), and as a beginner, I was initially confused about the difference between using the $set operator and the "upsert: true" option.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小姐丶请自重 2025-01-22 03:38:42

这就是文档所说的:

Mongo更新: $set

如果该字段不存在,$set 将添加具有指定值的新字段,前提是该新字段不违反类型约束。如果您为不存在的字段指定点式路径,$set 将根据需要创建嵌入文档来满足该字段的点式路径。

Mongo 更新:$upsert

如果文档与查询条件匹配,则 db.collection.update() 执行更新。

如果没有文档与查询条件匹配,则 db.collection.update() 会插入单个文档。

答案:本质上的区别在于,如果更新查询找到文档但未找到指定的字段,$set 运算符将创建一个新的字段。如果更新查询未找到文档,则更新函数会被确认,但不会更新或创建任何内容。

选项如果查询未找到指定的文档,将创建一个新的文档

如果查询结果匹配,$set 和 upsert 都将执行更新。

This is what the documentation says:

Mongo Update: $set

If the field does not exist, $set will add a new field with the specified value, provided that the new field does not violate a type constraint. If you specify a dotted path for a non-existent field, $set will create the embedded documents as needed to fulfill the dotted path to the field.

Mongo Update: $upsert

If document(s) match the query criteria, db.collection.update()performs an update.

If no document matches the query criteria, db.collection.update() inserts a single document.

ANSWER: Essentially the difference is that the $set operator will create a new field if the update query finds the document but not the field specified. If the update query doesn't find the document, the update function is acknowledged but nothing is updated or created.

The option <upsert: true> will create a new document if the query doesn't find the the document specified.

Both $set and upsert will perform an update if the query results in a match.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文