MongoDB 聚合 - 根据数据选择查找 collection。可以吗?

MongoDB aggregation - choose a lookup collection depending on the data. Can it be done?

我有一个 collection - "items"

我还有另外两个 collections - "books_details" & "fruits_details"。它们有不同的结构。

有些项目是 item_type:book,有些是 item_type:fruit。

每个项目都有一个 item_type_id 匹配相应 collection 中的文档。

我想根据 item_type.

显示相应 collection 中的详细信息的项目组合列表

好像是:

这可能吗?如果是,如何?

谢谢。

{
  "item_id": 1234,
  "item_type": "book",
  "item_type_id": 1
},
{
  "item_id": 5678,
  "item_type": "fruit",
  "item_type_id": 1
}

books_details

{
  "item_id": 1,
  "title": "Gone with the wind",
  "author": "Margaret Mitchell"
}

fruits_details

{
  "item_id": 1,
  "name": "Banana",
  "color": "yellow"
}

预期名单

{
      "item_id": 1234,
      "item_type": "book",
      "item_type_id": 1,
      "fruits_details": {},
      "books_details": {"title": "Gone with the wind", "author": "Margaret Mitchell"}
    },
    {
      "item_id": 5678,
      "item_type": "fruit",
      "item_type_id": 1,
      "fruits_details": {"name":"Banana","color":"yellow"},
      "books_details": {}
    }

您可以使用下面的aggregation

db.items.aggregate([
  { "$lookup": {
    "from": "fruits",
    "localField": "item_type_id",
    "foreignField": "item_id",
    "as": "fruits_details"
  }},
  { "$lookup": {
    "from": "books",
    "localField": "item_type_id",
    "foreignField": "item_id",
    "as": "books_details"
  }},
  { "$addFields": {
    "books_details": {
      "$cond": [{ "$eq": ["$item_type", "book"] }, "$books_details", {}]
    },
    "fruits_details": {
      "$cond": [{ "$eq": ["$item_type", "fruit"] }, "$fruits_details", {}]
    }
  }}
])