Insert Object inside an object in MongoDB
Dec 25, 2020
Here We’ll discuss how we can insert an object inside an existing object in MongoDB
$set plays an important role here as, If the field does not exist, $set will add a new field with the specified value…
Suppose we have an exiting document as following
{
“firstName”: “John”,
“lastName”: “Doe”,
“age”: 50,
“address”:{
“current address”: “USA”,
},
“metadata”:{
“Primary School”:”YES”,
“High School”:”YES”,
“Graduate”:”YES”,
“Post Graduate”:”NO”,
“Professional”:”YES”,
},
}
and the requirement is to insert following object inside address
“permanent address” : {
“state” : “UP”,
“country” : “India”
}
For this query will be
db.data.update({“firstName”: “John”}, {$set:{“address.permanent address”:{“state”: “UP”, “country”: “India”}}}
Have any doubt or query please reach out to me