我一直在将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"}}