如何部分更新MongoDB中的对象,以便新对象将与现有对象重叠/合并 [英] How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

查看:82
本文介绍了如何部分更新MongoDB中的对象,以便新对象将与现有对象重叠/合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此文档已保存在MongoDB中

Given this document saved in MongoDB

{
   _id : ...,
   some_key: { 
        param1 : "val1",
        param2 : "val2",
        param3 : "val3"
   }
}

需要保存具有来自外部世界的有关param2param3的新信息的对象

An object with new information on param2 and param3 from the outside world needs to be saved

var new_info = {
    param2 : "val2_new",
    param3 : "val3_new"
};

我想将新字段合并/覆盖在对象的现有状态上,以便不会删除param1

I want to merge / overlay the new fields over the existing state of the object so that param1 doesn't get removed

这样做

db.collection.update(  { _id:...} , { $set: { some_key : new_info  } } 

将导致MongoDB完全按照要求执行操作,并将some_key设置为该值.取代旧的.

Will lead to MongoDB is doing exactly as it was asked, and sets some_key to that value. replacing the old one.

{
   _id : ...,
   some_key: { 
      param2 : "val2_new",
      param3 : "val3_new"
   }
}

让MongoDB仅更新新字段(不明确地逐一说明)的方式是什么?得到这个:

What is the way to have MongoDB update only new fields (without stating them one by one explicitly)? to get this:

{
   _id : ...,
   some_key: { 
        param1 : "val1",
        param2 : "val2_new",
        param3 : "val3_new"
   }
}

我正在使用Java客户端,但任何示例都将不胜感激

I'm using the Java client, but any example will be appreciated

推荐答案

如果我正确理解了这个问题,则希望使用另一个文档的内容来更新一个文档,但是只使用尚未存在的字段来进行更新,而完全忽略已设置的字段(即使设置为另一个值).

If I understand the question correctly, you want to update a document with the contents of another document, but only the fields that are not already present, and completely ignore the fields that are already set (even if to another value).

无法在单个命令中执行此操作.

There is no way to do that in a single command.

您必须先查询文档,弄清楚您要$set的内容,然后进行更新(使用旧值作为匹配过滤器,以确保在两次更新之间不会出现并发更新).

You have to query the document first, figure out what you want to $set and then update it (using the old values as a matching filter to make sure you don't get concurrent updates in between).

对您的问题的另一种解读是,您对$set感到满意,但不想显式设置所有字段.那么您将如何传递数据?

Another reading of your question would be that you are happy with $set, but do not want to explicitly set all fields. How would you pass in the data then?

您知道您可以执行以下操作:

You know you can do the following:

db.collection.update(  { _id:...} , { $set: someObjectWithNewData } 

这篇关于如何部分更新MongoDB中的对象,以便新对象将与现有对象重叠/合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆