使用mongodb更新文档,参数upsert为true时,新生成文档包含哪些字段

本文详细解析了MongoDB中使用update方法时upsert参数为true的情况。具体介绍了两种不同场景下新文档如何生成,包括当<update>参数为替换文档时,新文档的内容直接取自该参数;当<update>参数包含更新运算符表达式时,新文档则综合<query>和<update>参数的内容进行创建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用mongo更新数据时,当upsert参数为true时且根据查询条件无结果时,mongo就要插入新纪录。

新纪录文档的内容跟查询条件和更新内容有关。

下面是官方文档的描述:

If upsert is true and no document matches the query criteria, update() inserts a single document. The update creates the new document with either:

  • The fields and values of the <update> parameter if the <update> parameter is a replacement document (i.e., contains only field and value pairs). If neither the <query> nor the <update> document specifies an _id field, MongoDB adds the _id field with an ObjectId value.
  • The fields and values of both the <query> and <update> parameters if the <update> parameter contains update operator expressions. The update creates a base document from the equality clauses in the <query> parameter, and then applies the update expressions from the <update> parameter. Comparisonoperations from the <query> will not be included in the new document.

更多信息查看原网址:https://docs.mongodb.com/v3.2/reference/method/db.collection.update/

这段话的意思就是:

1)如果<update>是替换文档(即仅包含字段和值对),那么新文档的内容就是<update>的字段和值。如果<query>和<update>文档都没有指定_id字段,MongoDB会添加带有ObjectId值的_id字段。也就是<query>中包含_id字段时,新文档就包含<query>中的_id字段

2)如果<update>参数包含更新运算符表达式,那么新文档的内容包含<query>和<update>参数的字段和值。新文档以<query>中的判等条件的字段和值对为基础(也就是<query>的比较操作不会包含在新文档中),然后应用<update>参数中的更新表达式,最终生成新文档的内容。

更新运算符表达式的具体内容参考:https://docs.mongodb.com/v3.2/reference/operator/update/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值