mongodb - 仅当 MongoDB 文档字段不存在时,如何更新它们?

标签 mongodb

我收集了 foo 文档,例如:

{site_id: 'xxx', title: {ru: 'a', en: 'b'}, content: {ru: 'a', en: 'b'}}
{site_id: 'xxx', title: {ru: 'c', de: 'd'}, content: {ru: 'c', de: 'd'}}

我需要更新多个可以存在或不存在的字段:

db.foo.update(
    { site_id: 'xxx'},
    { $set: {'title.de': '', 'content.de': ''}},
    {multi: true}
)

但是我需要像 $set 这样的东西,如果它存在就不会覆盖它。

最佳答案

您可以在更新语句中添加查询:

db.foo.update({'title.de': {$exists : false}}, {$set: {'title.de': ''}})

更新

对于您修改后的问题,我的解决方案如下所示 - 这对您有用吗? (如果不是,为什么?)

db.foo.update({site_id: 'xxx', 'title.de': {$exists : false}}, {$set: {'title.de': ''}, {multi: true})
db.foo.update({site_id: 'xxx', 'content.de': {$exists : false}}, {$set: {'content.de': ''}}, {multi: true})

关于mongodb - 仅当 MongoDB 文档字段不存在时,如何更新它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24824657/

相关文章:

node.js - 将nodejs应用程序上传到AWS EC2

mongodb - 有没有办法按嵌套集合对 Mongo 结果进行排序?

mongodb - Azure 门户中 Cosmos DB 的帐户 key 在哪里

node.js - Node Js - 如果连接中断,Mongoose find 不会抛出错误

mongodb - 快速存储大量文档到 mongoose

javascript - 用于计算返回文档中唯一 ID 的 Mongo 聚合速度很慢

python - 如何获得 MongoDB 的 Motor 驱动程序?

java - Neo4J 与 APOC 和 MongoDB 驱动程序,限制从 Mongo 返回的记录

mongoDB 不同,在同一个查询中在哪里?

javascript - mongodb mongoose find - 如何获取适用的字符串作为结果?