1

I have a mongo collection where docs have been already stored. The structure is of a single doc is something like this:

   "_id":ObjectId("55c3043ab165fa6355ec5c9b"),
   "address":{
      "building":"522",
      "coord":[
         -73.95171,
         40.767461
      ],
      "street":"East   74 Street",
      "zipcode":"10021"
   }
}

Now I want to update the doc by inserting a new field "persons" with value being a list of objects [{"name":"marcus", "contact":"420"}, {"name":"modiji", "contact":"111"}], so after insertion the above doc should look like this:

   "_id":ObjectId("55c3043ab165fa6355ec5c9b"),
   "address":{
      "building":"522",
      "coord":[
         -73.95171,
         40.767461
      ],
      "street":"East   74 Street",
      "zipcode":"10021"
   },
   "persons":[
      {
         "name":"marcus",
         "contact":"420"
      },
      {
         "name":"modiji",
         "contact":"111"
      }
   ]
}

Can anyone please help me with then correct $set syntax? Also, it would be really helpful if anyone can suggest an efficient way to update a key's value, which is a list of objects so that I can push some new objects inside the existing list.

1 Answer 1

6

You can use the updateOne command along with $set operator to achieve it.

db.<Collection-Name>.updateOne({
    "_id":ObjectId("55c3043ab165fa6355ec5c9b")
}, {
    "$set": {
        "persons":[
              {
                 "name":"marcus",
                 "contact":"420"
              },
              {
                 "name":"modiji",
                 "contact":"111"
              }
       ]
    }
})

If you want to push additional data into the array, you can use the below command.

db.<Collection-Name>.updateOne({
    "_id":ObjectId("55c3043ab165fa6355ec5c9b")
}, {
    "$push": {
        "persons": {
             "name":"sample",
             "contact":"1234"
        }
    }
})

To push multiple arrays of objects in a single command, use the below query

db.<Collection-Name>.updateOne({
    "_id":ObjectId("55c3043ab165fa6355ec5c9b")
}, {
    "$push": {
        "persons": {
            "$each": [
                {
                     "name":"sample1",
                    "contact":"5678"
                },
                {
                     "name":"sample2",
                    "contact":"90123"
                }
            ]
        }
    }
})
Sign up to request clarification or add additional context in comments.

1 Comment

thanks it works perfectly. Can you please also suggest a way to push multiple objects at once?

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.