简体   繁体   English

更新文档 mongodb nodejs 中的嵌套对象

[英]Update nested objects in document mongodb nodejs

I have this document in a mongodb collection:我在 mongodb 集合中有这个文档:

{
    _id :ObjectId("619ce75ca456eb79b75dc0c1")
    name : "John",
    car: {
        color: {
            red: 10
        }
    },
}

And I want update the car Object by adding a new key that is an abject (like color)我想通过添加一个卑鄙的新钥匙(如颜色)来更新汽车 Object

So I want to update my document like this:所以我想像这样更新我的文档:

{
    _id :ObjectId("619ce75ca456eb79b75dc0c1"),
    name : "John",
    car: {
        color: {
            red: 10
        },
        brand :{
            nissan : 1212
        }
    },
}

How can I do it with mongodb updateOne?如何使用 mongodb updateOne 做到这一点? My code removes last keys from car object and just adds the new key:我的代码从汽车 object 中删除了最后一个键,并添加了新键:

var car = {}
   car["brand"] = {
      nissan : 1212
   }

db.collection("collection").updateOne(
        {name : "John"} , 
        {$set : { car : car}}
      );
    }

//Current output: 
//{
//  _id :ObjectId("619ce75ca456eb79b75dc0c1"),
//  name : "John",
//  car: {
//       brand :{
//           nissan : 1212
//      }
//  },
//}


//The output  I want: 
//{
//  _id :ObjectId("619ce75ca456eb79b75dc0c1"),
//  name : "John",
//  car: {
//      color: {
//          red: 10
//      },
//      brand :{
//           nissan : 1212
//      }
//  },
//}

And another question, If the brand or color or every key that we want to add our color object was a variable, How can we add it to color object?还有一个问题,如果我们想要添加颜色 object 的品牌或颜色或每个键是一个变量,我们如何将它添加到颜色 object 中?

db.collection.updateOne({ "name": "John" }, { $set: { "car.brand.nissan": 1212 } } )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM