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

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


版权声明:本文为lieying411原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。