Dhanendra
Dhanendra

Reputation: 113

How to insert array/list of objects in existing MongoDB document?

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.

Upvotes: 1

Views: 9538

Answers (1)

hhharsha36
hhharsha36

Reputation: 3349

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

Upvotes: 6

Related Questions