Rakesh
Rakesh

Reputation: 53

MongoDB insert object inside an object

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..

Upvotes: 3

Views: 11990

Answers (3)

perona chan
perona chan

Reputation: 191

please find the below code, its working as expected

worked !!

cmiw !!

db.getCollection('PetCare').update(
  {"email" : "[email protected]"},
  {"$set":
    {"userDetails.address":
      {"country":"India","city":"Blore"}
    }
})

Upvotes: -1

Celia
Celia

Reputation: 355

Try the following:

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

Upvotes: 7

Jonathan Michalik
Jonathan Michalik

Reputation: 1532

The $push operator you're currently using is intended to add a value to an array, so that won't get the job done here.

If you're wanting to update a document with a new property, you'll want to use the $set operator:

db.test.update({contactNumber: "xxx"}, {$set: {address: {country: "India", city: "Blore"}}})

Upvotes: 3

Related Questions