MongoDB聚合-根据数据选择查找集合。能做到吗?

时间:2018-12-11 18:25:09

标签: mongodb aggregation

我有一个收藏集-“商品”

我还有另外两个收藏集-“ books_details”和“ fruits_details”。它们具有不同的结构。

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

每个项目都有一个item_type_id,该ID与相应集合中的文档匹配。

我要根据item_type显示具有相应集合详细信息的项目组合列表。

似乎是:

  • 我需要执行两个不同的$ lookup阶段并将其合并。这样做没有成功。

  • 进行一个$ lookup并将结果作为第二个$ lookup阶段的基础,并将其合并。这样做没有成功。

  • 我需要根据item_type进行$ lookup。找不到解决方法。

这可能吗?如果是,怎么办?

谢谢。

项目

{
  "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": {}
    }

1 个答案:

答案 0 :(得分:1)

您可以在aggregation下使用

landlord