【问题标题】:How to update particular array index in mongoDB using a variable如何使用变量更新 mongoDB 中的特定数组索引
【发布时间】:2017-07-11 20:56:50
【问题描述】:

我正在创建两个集合,一个是临时创建的,然后从主集合“填充”到另一个文档中。

我很难理解如何以类似于下面的方式更新数组的特定索引。

function stuffDepartmentsIntoLocations() {
    var ops = [];

    db.HR.find().forEach(function(country) 
        {
            for(var i=0;i < country.location.length; i++) {
                db.tempDEPTS.find({"LOCATION_ID":location.LOCATION_ID}).forEach(function(dept)
                    {
                        ops.push(
                            {
                                    "updateOne": 
                                {
                                        "filter": {"_id": country._id },
                                        "update\": {"$push": {"location[i].department":dept}}
                                        }
                                } 
                            );
                        if ( ops.length == 1000 ) {
                                db.HR.bulkWrite(ops,{ "ordered": false });
                                ops = [];
                        }
                    }               
                );          
             }      
      }
    );

   if ( ops.length > 0 ) {
     db.HR.bulkWrite(ops,{ "ordered": false });
   }

 return true;
}"

这似乎不起作用:

"update": {"$push": {"location[i].department":dept}}

错误如下:

{ "serverUsed" : "127.0.0.1:27017" , "retval" : true , "ok" : 1.0} { “serverUsed”:“127.0.0.1:27017”,“ok”:0.0,“errmsg”: “ReferenceError:未定义位置 :\nstuffDepartmentsIntoLocations/

人力资源收集文档如下所示:

我尝试添加的临时集合中的部门文档如下:

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    啊啊啊……刚看到,以前有一个forEach但是改成索引数组了:

    这个:

    db.tempDEPTS.find({"LOCATION_ID":location.LOCATION_ID}).forEach(function(dept)
    

    应该是这样的:

    db.tempDEPTS.find({"LOCATION_ID":country.location[i].LOCATION_ID}).forEach(function(dept)
    

    现在我的部门根据 location_id 被塞进位置文件:

    必须是一种更好的方法,但似乎可行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-04
      • 2013-01-13
      • 2016-06-09
      • 2016-11-04
      • 2014-03-27
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      相关资源
      最近更新 更多