我一直在使用 MongoDB 和 .NET core 和 Node.js。这个问题特定于我正在处理的节点项目,但我认为客户端语言与我的问题无关。
我有一个文档,其中包含下面的名称和地址当前(“add_current”)等元素:
{
"_id" : ObjectId("5d858718c1d9f856881dc9ce"),
...
"name": "John Doe",
"add_current" :
{
"add1" : "456 Old Ave.",
"city" : "Stafford",
"state" : "VA",
"zip" : "23234"
},
...
}
有时我只是像这样更新子对象的某些部分:
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 字段。我不想那样做。
我正在寻找最有效的方法来更新 name 和 add_current.add1 而不删除其他字段(如 add_current.state)。我意识到有很多方法可以通过多次触摸数据记录(.findOne(...)
然后.update(...)
)来做到这一点。有没有办法通过一次.update(...)
触摸来做到这一点?
您正在将 add_current 的值设置为 {add1: "123 New Street"}
尝试 {$set:{"add_current.add1": "123 New Street"}}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句