mongodb 查找复杂的对象数组

gev0vcfq  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(138)

我是MongoDB的新手,我正在努力进行一个$查找并得到想要的结果。如果有人能帮助我,我将非常感谢

收集组

{
  "_id": "any_id",
  "groups": [
    {
      "group_id": "group_id_1",
      "departments": [
        {
          "department_id": "id_1"
        },
        {
          "department_id": "id_2"
        }
      ]
    }
  ]
}

收款部门

{
  "_id": "id_1",
  "name": "name 1"
},
{
  "_id": "id_2",
  "name": "name 2"
},
{
  "_id": "id_3",
  "name": "name 3"
}

预期结果

{
  "_id": "any_id",
  "groups": [
    {
      "group_id": "group_id_1",
      "departments": [
        {
          "department_id": "id_1",
          "name": "name 1"
        },
        {
          "department_id": "id_2",
          "name": "name 2"
        }
      ]
    }
  ]
}
2skhul33

2skhul331#

这里的解决方案:Demo@mongoplayground
第一步:加入部门集合
第二步:Map生成的Array对象,并根据条件进行合并
Mongodb聚合管道:https://mongoplayground.net/p/5ebIgizA3_8

db.workoutDetailSchema.aggregate([
  {
    $lookup: {
      from: "departments",
      localField: "groups.departments.department_id",
      foreignField: "_id",
      as: "result"
    }
  },
  {
    "$project": {
      "groups": {
        $map: {
          input: "$groups",
          as: "group",
          in: {
            $mergeObjects: [
              "$$group",
              {
                "departments": {
                  $map: {
                    input: "$$group.departments",
                    as: "dept",
                    in: {
                      $mergeObjects: [
                        "$$dept",
                        {
                          $first: {
                            $filter: {
                              input: "$result",
                              cond: {
                                $eq: [
                                  "$$dept.department_id",
                                  "$$this._id"
                                ]
                              }
                            }
                          }
                        }
                      ]
                    }
                  }
                }
              }
            ]
          }
        }
      },
    }
  },
  {
    $project: {
      "groups.departments._id": 0
    }
  }
])

一月一日

[
  {
    "_id": "any_id",
    "groups": [
      {
        "departments": [
          {
            "department_id": "id_1",
            "name": "name 1"
          },
          {
            "department_id": "id_2",
            "name": "name 2"
          }
        ],
        "group_id": "group_id_1"
      }
    ]
  }
]

相关问题