Update nested objects in document mongodb

I have this document in a mongodb collection :

{
    _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)

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 ? My code removes last keys from car object and just adds the new key :

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
//      }
//  },
//}


from Recent Questions - Stack Overflow https://ift.tt/3cDRQt0
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)