Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB insert object inside an object

Tags:

json

mongodb

Please suggest me on how to insert an object inside an object. Sample collection

{
"_id" : ObjectId("57556cec9d66a6c26b19ce06"),
"email" : "[email protected]",
"password" : "1235466",
"typeOfUser" : 1,
"userDetails" : {
    "firstName" : "David",
    "lastName" : "Beckham",
    "contactNumber" : "12345678989"
}

}

I would like to add another object called address object inside this. something like this

{
"_id" : ObjectId("57556cec9d66a6c26b19ce06"),
"email" : "[email protected]",
"password" : "1235466",
"typeOfUser" : 1,
"userDetails" : {
    "firstName" : "David",
    "lastName" : "Beckham",
    "contactNumber" : "12345678989"
     "address" : {
        "country" : "",
        "state" : ""
     }
  }

}

Please suggest me on how to insert values for address object..

What I have tried?

db.getCollection('PetCare').update({"contactNumber":"12345678989"},{"$push":{"address":{"country":"India","city":"Blore"}}})

but it does not update..

like image 315
Rakesh Avatar asked Jan 27 '26 07:01

Rakesh


1 Answers

Try the following:

db.getCollection('PetCare').update({"userDetails.contactNumber":"12345678989"},{"$set":{"userDetails.address":{"country":"India","city":"Blore"}}})
like image 118
Celia Avatar answered Jan 28 '26 20:01

Celia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!