【问题标题】:MongoDB aggregation - choose a lookup collection depending on the data. Can it be done?MongoDB 聚合 - 根据数据选择查找集合。可以做到吗?
【发布时间】:2018-12-13 01:26:05
【问题描述】:

我有一个收藏 - “项目”

我还有另外两个系列——“books_details”和“fruits_details”。它们有不同的结构。

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

每个项目都有一个与相应集合中的文档匹配的 item_type_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": {}
    }

【问题讨论】:

  • 除非你有充分的理由,否则不要尝试使用 NoSQL 构建关系数据库。我建议您将所有内容存储在一个集合中。

标签: mongodb aggregation


【解决方案1】:

您可以在下面使用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", {}]
    }
  }}
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-14
    • 2022-01-03
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 2019-02-11
    相关资源
    最近更新 更多