外域是对象数组时的MongoDB查找

时间:2019-02-10 13:52:15

标签: mongodb nosql mongodb-query aggregation-framework

我有两个收藏集initiativesresources

初始文档示例:

{
    "_id" : ObjectId("5b101caddcab7850a4ba32eb"),
    "name" : "AI4CSR",
    "ressources" : [
        {
            "function" : ObjectId("5c3ddf072430c46dacd75dbb"),
            "participating" : 0.1,
         },
         {
            "function" : ObjectId("5c3ddf072430c46dacd75dbc"),
            "participating" : 5,
         },
         {
            "function" : ObjectId("5c3ddf072430c46dacd75dbb"),
            "participating" : 12,
         },
         {
            "function" : ObjectId("5c3ddf072430c46dacd75dbd"),
            "participating" : 2,
         },
    ],
}

资源文档:

{
    "_id" : ObjectId("5c3ddf072430c46dacd75dbc"),
    "name" : "Statistician",
    "type" : "FUNC",
}

所以我想返回每个资源并包含参与的总和。为此,我需要加入两个集合。

db.resources.aggregate([
{
    "$match": { type: "FUNC" }
},
{
    "$lookup": {
            "from": "initiatives",
            "localField": "_id",
            "foreignField": "initiatives.resources",
            "as": "result"
        }
},
])

但是首先我需要展开异域数组。

预期输出示例:

{
        "function" : "Data Manager"
        "participation_sum": 50
}
{
        "function" : "Statistician"
        "participation_sum": 1.5
}
{
        "function" : "Supply Manage"
        "participation_sum": 0
}

1 个答案:

答案 0 :(得分:1)

您可以在mongodb 3.6 及更高版本

中使用以下聚合
db.resources.aggregate([
  { "$match": { "type": "FUNC" } },
  { "$lookup": {
    "from": "initiatives",
    "let": { "id": "$_id" },
    "pipeline": [
      { "$match": { "$expr": { "$in": ["$$id", "$ressources.function"] } } },
      { "$unwind": "$ressources" },
      { "$match": { "$expr": { "$eq": ["$ressources.function", "$$id"] } } },
      { "$group": {
        "_id": "$ressources.function",
        "participation_sum": { "$sum": "$ressources.participating" }
      }}
    ],
    "as": "result"
  }}
])