我收集了 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/