首页 > 解决方案 > MongoDB 查找并映射 2 个结果数组

问题描述

我在 MongoDB 聚合管道中查找后有 2 个数组字段。

第一个

[
    {
        "colorId": "60828a1b216b0972da695f2a",
        "name": "Exellent",
        "description": "Great work"
    }
]

第二个

[
    {
        "_id": "60828a1b216b0972da695f2a",
        "colorName": "Green",
        "hexColorCodes": "#2D9D78",
        "sequence": 1,
        "isActivated": true,
        "created_at": "2021-04-23T08:49:31.729Z",
        "updated_at": "2021-04-23T08:49:31.729Z",
        "__v": 0,
        "isDefault": true
    }
]

我想要的结果是

[
  {
    "colorId": "60828a1b216b0972da695f2a",
    "name": "Exellent",
    "description": "Great work",
    "colorName": "Green",
    "hexColorCodes": "#2D9D78"
  }
]

然后我想映射colorNamehexColorCodes第一个数组。这是我的聚合管道

db.collection.aggregate([
{
      $lookup: {
        from: "color_tags",
        localField: "colors.colorId",
        foreignField: "_id",
        as: "tempColors",
      },
    },
    {
      $addFields: {
        stages3: {
          $map: {
            input: "$colors",
            in: {
              $mergeObjects: [
                "$$this",
                {
                  $arrayElemAt: [
                    "$tempColors",
                    {
                      $indexOfArray: [
                        "$tempColors._id",
                        "$$this.colors.colorId",
                      ],
                    },
                  ],
                },
              ],
            },
          },
        },
      },
    }
])

但结果不是我所期望的。它映射了不正确的 ID。请建议。

标签: javascriptdatabasemongodbmongooseaggregate

解决方案


  • $mapfirst迭代数组的循环
  • $filtersecond迭代数组循环并匹配colorId_id返回匹配结果
  • $arrayElemAt获取第一个匹配元素
  • $mergeObjects将当前对象与second数组的返回结果合并
  {
    $project: {
      first: {
        $map: {
          input: "$first",
          as: "f",
          in: {
            $mergeObjects: [
              "$$f",
              {
                $arrayElemAt: [
                  {
                    $filter: {
                      input: "$second",
                      cond: { $eq: ["$$this._id", "$$f.colorId"] }
                    }
                  },
                  0
                ]
              }
            ]
          }
        }
      }
    }
  }

如果要生成特定字段$project,请在最后添加一个阶段,

  {
    $project: {
      "first.colorId": 1,
      "first.name": 1,
      "first.description": 1,
      "first.colorName": 1,
      "first.hexColorCodes": 1
    }
  }

操场


推荐阅读