如何在mongodb中联接两个表并将其推入数组

时间:2018-12-13 06:44:10

标签: javascript mongodb mongodb-query

这里我有两个集合OrganizationsGroups,我的要求是我要在“组织”表中检查oldOrgID,并且必须取schoolCode和{{1 }}并推入schoolName,直到我完成为止,

现在我的问题是mainData表,我必须拿Organizations,我必须签入orgIDGroups,如果假设匹配意味着我必须拿{ otherIds.orgID表中的{1}}推送到name

  

组织:

Groups
  

组:

mainData
  

我的代码

{
    "_id" : ObjectId("5c11efebd9cb4d35f47d6bd0"),
    "orgID" : "5b6c82462fb9ca35444d0ba2",
    "name" : "The Punjab Public School",
    "oldOrgID" : "176348"
}
  

获取输出

/* 1 createdAt:12/13/2018, 11:06:02 AM*/
{
    "_id" : ObjectId("5c11efc2d9cb4d35f47d6bcf"),
    "groupID" : "2",
    "name" : "8 B",
    "otherIds" : {
        "orgID" : "ORG1"
    },
    "version" : NumberInt(1)
},

/* 2 createdAt:12/13/2018, 11:05:08 AM*/
{
    "_id" : ObjectId("5c11ef8cd9cb4d35f47d6bce"),
    "groupID" : "1",
    "name" : "8 A",
    "otherIds" : {
        "orgID" : "ORG1"
    },
    "version" : NumberInt(1)
}
  

预期产量

 var mainData = {};
var schoolCode = 176348 ;

db.Organizations.find({"oldOrgID" : schoolCode})
// .limit(1)
// .skip(15)
.forEach(function(doc){
    var OrgID = doc.orgID;
    if(mainData[OrgID] === undefined )
    {
      mainData[OrgID] = {}; // org name undefined means we are making empty object here
    }  
     mainData[OrgID]['schoolCode']  = doc.oldOrgID;
     mainData[OrgID]['schoolName']  = doc.name;

});
mainData
  

聚合代码

{
    "5b6c82462fb9ca35444d0ba2" : {
        "schoolCode" : "176348",
        "schoolName" : "The Punjab Public School"
    }
}
  

输出

{
    "5b6c82462fb9ca35444d0ba2" : {
        "schoolCode" : "176348",
        "schoolName" : "The Punjab Public School",
        "group-section" : 
                    [
                            {
                                "name" : "8 B"
                            },
                            {
                                "name" : "8 A"
                            }
                    ]
    }
}

2 个答案:

答案 0 :(得分:1)

您可以尝试使用汇总查询并使用

LOOKUP操作:

了解更多:https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

您可以这样:

db.Organizations.aggregate([{
   $lookup:
     {
       from: "Groups" // <collection to join>,
       localField: "oldOrgID"  // <field from the input documents>,
       foreignField: "otherIds.orgId" // <field from the documents of the "from" collection>,
       as: "group-section" <output array field>
     }
}]);

希望这能给您带来想法。

答案 1 :(得分:1)

$ lookup是聚合查询的管道阶段之一,因此您需要按以下方式使用Mongo Aggregation查询:

db.collection.aggregate([
  {
    $match: {
      oldOrgID: "176348"
    }
  },
  {
    $lookup: {
      from: "other",
      localField: "orgID",
      foreignField: "otherIds.orgID",
      as: "group-section"
    }
  },
  {
    $project: {
      "group-section._id": 0,
      "group-section.groupID": 0,
      "group-section.otherIds": 0,
      "group-section.version": 0
    }
  }
])