MongoDB $查找具有引用 objectId 的对象数组

MongoDB $lookup on array of objects with reference objectId

我有订单集合,我正在从中获取数据,如下所示:

 [
  {
    "_id": "628216b7b30bb8aa80c8fd1a",
    "promotionsDetails": {
      "companyTotalPrice": 27,
      "promotionsData": [
        {
          "_id": "621de063bb5f9f0bf510897f",
          "price": 27,
          "companyId": "621dd85eb45ca2ae292d9a36"
        },
        {
          "_id": "621de063bb5f9f0bf510897d",
          "price": 19,
          "companyId": "621dd85eb45ca2ae292d9a32"
        }
      ]
    }
  },
  {
    "_id": "628214fcb30bb8aa80c8fd18",
    "promotionsDetails": {
      "companyTotalPrice": 46,
      "promotionsData": [
        {
          "_id": "621de063bb5f9f0bf510897f",
          "price": 46,
          "companyId": "621dd85eb45ca2ae292d9a32",
        }
      ]
    },
  }
]

我想做的是使用数组中每个对象中的 companyId objectId 从公司集合中获取公司详细信息,如下所示:

    [
  {
    "_id": "628216b7b30bb8aa80c8fd1a",
    "promotionsDetails": {
      "companyTotalPrice": 27,
      "promotionsData": [
        {
          "_id": "621de063bb5f9f0bf510897f",
          "price": 27,
          "companyId": "621dd85eb45ca2ae292d9a36",
          "companyData": { "title": "..." }
        },
        {
          "_id": "621de063bb5f9f0bf510897d",
          "price": 19,
          "companyId": "621dd85eb45ca2ae292d9a32",
          "companyData": { "title": "..." }
        }
      ]
    }
  },
  {
    "_id": "628214fcb30bb8aa80c8fd18",
    "promotionsDetails": {
      "companyTotalPrice": 46,
      "promotionsData": [
        {
          "_id": "621de063bb5f9f0bf510897f",
          "price": 46,
          "companyId": "621dd85eb45ca2ae292d9a32",
          "companyData": { "title": "..." }
        }
      ]
    }
  }
]

我已经尝试使用查找和管道,但我没有得到想要的结果,谢谢!

在这里,为了更清楚地看一下 Mongo playground

db.Orders.aggregate([
  {
    $unwind: "$promotionsDetails.promotionsData"
  },
  {
    "$lookup": {
      "from": "Company",
      "localField": "promotionsDetails.promotionsData.companyId",
      "foreignField": "_id",
      "as": "promotionsDetails.promotionsData.companyData"
    }
  },
  
])

实际$lookup支持数组,所以不需要$unwind和改变结构。这将 return 您的预期结果:

db.Orders.aggregate([
  {
    $lookup: {
      from: "Company",
      localField: "promotionsDetails.promotionsData.companyId",
      foreignField: "_id",
      as: "companyfullData"
    }
  },
  {
    $set: {
      "promotionsDetails.promotionsData": {
        $map: {
          input: "$promotionsDetails.promotionsData",
          in: {
            $mergeObjects: [
              "$$this",
              {
                companyData: {
                  $arrayElemAt: [
                    "$companyfullData",
                    {$indexOfArray: ["$companyfullData.id", "$$this.id"]}
                  ]
                }
              }
            ]
          }
        }
      }
    }
  },
  {$unset: "companyfullData"}
])

Playground