1

I have a document like this on my table UserCollection:

{
  "FirstName": "Mohammad",
  "LastName": "Waheed", 
}

I want to add another array object to it how can I do that.?

  "PhoneNumbers":[  //this object is not present in the table
        {
          "number": NumberInt(8332045764) 
        },
        {
          "number": NumberInt(1234567890) 
        } 
     ] 

My expected result is like this:

{
  "FirstName": "Mohammad",
  "LastName": "Waheed",
  "PhoneNumbers":[  
        {
          "number": NumberInt(8332045764) 
        },
        {
          "number": NumberInt(1234567890) //when i call this method again it should store like this
        } 
     ] 
}

This is what I have tried : 1.only getting that single record 2. $number has data of phone number

return $db->update(array('$set' => array("PhoneNumbers.$.number" => $number))); 
Mr world wide
  • 4,696
  • 7
  • 43
  • 97
  • possible duplicate of https://stackoverflow.com/questions/18438362/adding-new-element-to-array-in-mongodb – mtj Dec 19 '17 at 06:40

1 Answers1

3

You can use $push command to add multiple numbers to list

   model.update({'FirstName':'Mohammad'}, {$push:{PhoneNumbers: NumberInt(1234567890)}}, function (err, updatedModelObj) {
if (err) {
   console.log(err);

}
callback(updatedModelObj);

})
Dimuthu
  • 1,611
  • 1
  • 14
  • 16
  • In your answer `{'FirstName':'Mohammad'},` will update this value as well or it is like `where` condition..? – Mr world wide Dec 20 '17 at 03:21
  • I have tried with these $push,$set,$addtoset and for query update,findmodify both none are working cant able to where I am doing wrong.! – Mr world wide Dec 20 '17 at 03:23
  • Yes it is like where condition. Here i have used mongoose update, if you can update code, i can check it - for more info http://mongoosejs.com/docs/guide.html – Dimuthu Dec 20 '17 at 09:01