MONGODB:在数组中添加新的键值

时间:2016-12-06 04:57:20

标签: mongodb insert

下面是我要添加新键值的数组:---

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

如何将新的键值添加到数组中,请提前帮助我。

2 个答案:

答案 0 :(得分:0)

要在数组中添加新的key: val,您可以在更新中使用$push中的update

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

像:

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

添加多个key: value可以使用$each$push这样的代码

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

答案 1 :(得分:-1)

您可以执行pushupdateThis可以为您提供见解:

例如:

db.col.update(
    { name: 'doc'}, 
    {$push: {'color': {name: 'Green'}}}
)
相关问题