3

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

3 Answers 3

7

Try the following:

db.getCollection('PetCare').update({"userDetails.contactNumber":"12345678989"},{"$set":{"userDetails.address":{"country":"India","city":"Blore"}}})
Sign up to request clarification or add additional context in comments.

Comments

3

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"}}})

Comments

-1

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"}
    }
})

1 Comment

Aside from a different property to look up a document (which is not the same as the OP specified), this is identical to an already-posted, upvoted, accepted answer from almost 5 years ago.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.