MongoDB是否可以在不删除更新数据中未包含的现有元素的情况下更新文档 [英] Does MongoDB have a way to update a document without dropping existing elements not contained in the update data

查看:101
本文介绍了MongoDB是否可以在不删除更新数据中未包含的现有元素的情况下更新文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在将MongoDB与.NET核心和Node.js一起使用.这个问题特定于我正在处理的节点项目,但是我认为客户端语言与我的问题无关.

I have been using MongoDB with both .NET core and Node.js. This question is specific to a node project I am working on, but I think the client language is irrelevant to my questions.

我有一个文档,其中包含诸如名称和当前地址(以下简称"add_current")之类的元素:

I have a document that has elements like name and address current ("add_current") below:

{
   "_id" : ObjectId("5d858718c1d9f856881dc9ce"),
   ...
   "name": "John Doe",
   "add_current" : 
   {
      "add1" : "456 Old Ave.",
      "city" : "Stafford",
      "state" : "VA",
      "zip" : "23234"
   },
   ...
}

有时候,我只是在更新子对象的某些部分,例如:

Sometimes I am just updating some parts of the child object like this:

const updateDocument2 = function (db, callback) {
    const collection = db.collection('documents');
    collection.update(
        { 
            '_id': ObjectID("5d858718c1d9f856881dc9ce") 
        },
        {
            $set: {
                name: "John Doe Jr.",
                add_current: {
                    add1: "123 New Street",
                }

            }
        }, function (err, result) {
            console.log("Updated the document");
            callback(result);
        });
}

当我执行上面的$set时,将删除字段city,state和zip.我不想那样做.

When I execute the $set above, I delete the fields city, state and zip. I don't want to do that.

我正在寻找更新名称和add_current.add1而不删除其他字段(例如add_current.state)的最有效方法.我意识到可以通过多次触摸数据记录(.findOne(...)然后.update(...))来执行此操作.有没有办法通过一次.update(...)触摸来做到这一点?

I am seeking the most efficient way to update name and add_current.add1 without deleting other fields (like add_current.state). I realize that there are ways to do this with multiple touches to the data record (.findOne(...) then .update(...)). Is there a way to do it with a single .update(...) touch?

推荐答案

您正在将add_current的值设置为{add1: "123 New Street"}

you are setting add_current's value to {add1: "123 New Street"}

尝试{$set:{"add_current.add1": "123 New Street"}}

这篇关于MongoDB是否可以在不删除更新数据中未包含的现有元素的情况下更新文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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