Insert Object inside an object in MongoDB

JS Developers
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…

Photo by Campaign Creators on Unsplash

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

Git- github.com/sachin9663

Linkedin- https://www.linkedin.com/in/sachinkumar9663

--

--

JS Developers
JS Developers

No responses yet