1

Below is my array where i want to add new Key Value:---

"color" : [
            {
                    "name" : "Blue"
            },
            {
                    "name" : "Red"
            }
    ]

I want to insert new key value as a green color into my array,like this;
"color" : [
          {
                "name" : "Blue"
        },
        {
                "name" : "Red"
        },
        {
                "name" : "Green"
        }]

How to add new key value into array,help me,thanks in advance.

Neha B
  • 75
  • 3
  • 9

2 Answers2

0

To add new key: val in an array you can use $push in update in update

db.collectionName.update(query,{ $push: { "array": obj }},option, callback);

like:

var newObj = {"name":"green"};
db.collectionName.update({_id: givenId},
       { $push: { "color": newObj }},
       function(err, result) {
         if(err) {
           // return  error
         }
        //return success
});

to add multiple key: value can use $each and $push like this code

var keyValArray= [{"name":"green"},{"name":"white"}];
db.collectionName.update({_id: givenId},
       { $push: { "color": {$each: keyValArray} }},
       function(err, result) {
          if(err) {
             // return  error
          }
          //return success
});
Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68
-1

You can either do a push or an update. This can give you an insight:

ex:

db.col.update(
    { name: 'doc'}, 
    {$push: {'color': {name: 'Green'}}}
)
Community
  • 1
  • 1
Jehoshuah
  • 671
  • 2
  • 9
  • 20