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

编程入门 行业动态 更新时间:2024-10-11 03:24:58
本文介绍了仅当不存在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文档字段时,才如何更新它们?

本文发布于:2023-07-21 03:37:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1173708.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不存在   字段   文档   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!