【问题标题】:MONGODB : ADD New Key Value in ArrayMONGODB:在数组中添加新的键值
【发布时间】:2016-12-06 04:57:20
【问题描述】:

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

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

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

【问题讨论】:

    标签: mongodb insert


    【解决方案1】:

    要在数组中添加新的key: val,您可以在更新中使用$push in 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
    });
    

    【讨论】:

    • 型号名称是什么意思?
    • 而不是ModelName 使用db.collectionName
    • "errmsg" : "字段 'color' 必须是一个数组,但在文档 {_id: ObjectId('55b85a63e9a22d5624711eb3')} 中属于 Object 类型,它给出了这个错误
    • 这意味着在你的集合中color 不是一个数组
    • 如果您的 color 是您显示的数组,那么应该可以正常工作。再次检查您的结构。或者对于那个 id 可以使用任何 GUI 检查结构
    【解决方案2】:

    您可以使用pushupdateThis可以给你一个见解:

    例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      相关资源
      最近更新 更多