Reputation: 594
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?
Upvotes: 0
Views: 874
Reputation: 1274
you are setting add_current's value to {add1: "123 New Street"}
try {$set:{"add_current.add1": "123 New Street"}}
Upvotes: 3