databasemongodbnosqlinsert-updatefindandmodify

How to add new object to existing data in mongo


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))); 

Solution

  • 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);
    
    })