Does MongoDB have a way to update a document without dropping existing elements not contained in the update data

谁说胖子不能爱 提交于 2020-04-18 07:15:23

问题


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.

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);
        });
}

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

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?


回答1:


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

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



来源:https://stackoverflow.com/questions/58081435/does-mongodb-have-a-way-to-update-a-document-without-dropping-existing-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!