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

查看:34
本文介绍了如何部分更新 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天全站免登陆