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
// }
// },
//}
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?
db.collection.updateOne({ "name": "John" }, { $set: { "car.brand.nissan": 1212 } } )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.