本文介绍了仅当不存在MongoDB文档字段时,才如何更新它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个集合foo,其中包含以下文件:
I have collection foo with documents like:
{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'}}我需要更新多个可以存在或不存在的字段:
I need to update multiple fields which are can exists or not:
db.foo.update( { site_id: 'xxx'}, { $set: {'title.de': '', 'content.de': ''}}, {multi: true} )但是我需要类似$set的东西,如果存在,它将不会覆盖值.
But I need something like $set which will not overwrite value if it exists.
推荐答案您可以在更新语句中添加查询:
You can add a query to your update statement:
db.foo.update({'title.de': {$exists : false}}, {$set: {'title.de': ''}})更新
对于您提出的问题,我的解决方案看起来像这样-对您有用吗? (如果没有,为什么?)
Update
For your modified question my solution looks like this - would that work for you? (If not, why?)
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文档字段时,才如何更新它们?
发布评论