【发布时间】:2017-07-13 06:49:21
【问题描述】:
我正在一个集合中的 mongoDB 中创建一个 country->locations 文档。
然后,我将创建一个单独的临时集合作为 ETL 作业(部门->员工)的一部分。
然后我想在 location_id 上的匹配项上插入与位置相关的部门。
这是位置文件(国家->位置):
这里是临时集合中的部门文档(department->employees):
我想遍历每个位置记录,然后找到匹配的部门并将它们添加到位置内的“部门”数组中,但我很挣扎:
到目前为止的JavaScript是:
function stuffDepartmentsIntoLocations() {
var ops = [];
var departments = function() {
this.deptsArray = [];
};
db.HR.find().forEach(function(country)
{
for(var i=0;i < country.locations.length; i++) {
departments.deptsArray= [];
db.tempDEPTS.find({"LOCATION_ID":country.locations[i].LOCATION_ID}).forEach(function(dept)
{
departments.deptsArray.push(dept);
});
db.tempDEPTS.find({"LOCATION_ID":country.locations[i].LOCATION_ID}).forEach(function(dept)
{
ops.push(
{
"updateOne":
{
"filter": {"_id": country._id },
"update": {"$push": {"locations": {$each: [] ,$position: i }}}
}
}
);
if ( ops.length == 1000 ) {
db.HR.bulkWrite(ops,{ "ordered": false });
ops = [];
}
}
);
}
}
);
if ( ops.length > 0 ) {
db.HR.bulkWrite(ops,{ "ordered": false });
}
return true;
}
但这不起作用,我没有看到任何插入。
我想要得到的是相关位置(与 LOCATION_ID 匹配)内的新“部门”数组,然后将 1 个或多个部门文档插入到数组中。即类似这样的东西(简化为理解)。
但是您可以看到创建了一个部门数组,其中插入了临时集合中的所有部门文档(“部门”需要是一个数组,即使只有一个部门)。
任何建议表示赞赏。
【问题讨论】:
-
我怀疑我应该使用 $lookup 或者 $out
标签: mongodb