代码之家  ›  专栏  ›  技术社区  ›  Ayoub k

当外部字段是对象数组时,MongoDB查找

  •  2
  • Ayoub k  · 技术社区  · 6 年前

    我有两件收藏品 initiatives resources :

    主动权 文档示例:

    {
        "_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,
             },
        ],
    }
    

    和A 资源 文件:

    {
        "_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 回复  |  直到 6 年前
        1
  •  1
  •   Ashh    6 年前

    您可以将下面的聚合与MongoDB一起使用 三点六 及以上

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