如何在 MongoDB 聚合管道中执行嵌套“连接”(连接 3 个或更多集合)?

2023-12-10

假设 MongoDB 中有 3 个假设的集合:customers, orders, and orderItems.

每个客户有多个订单,每个订单有多个订单项目。

以下是这 3 个集合的一些示例数据:

顾客

[
    {
        customer_id: 1,
        name: "Jim Smith",
        email: "[email protected]"
    },
    {
        customer_id: 2,
        name: "Bob Jones",
        email: "[email protected]"
    }
]

orders

[
    {
        order_id: 1,
        customer_id: 1
    },
    {
        order_id: 2,
        customer_id: 1
    }
]

订单项目

[
    {
        order_item_id: 1,
        name: "Foo",
        price: 4.99,
        order_id: 1
    },
    {
        order_item_id: 2,
        name: "Bar",
        price: 17.99,
        order_id: 1
    },
    {
        order_item_id: 3,
        name: "baz",
        price: 24.99,
        order_id: 2
    }
]

期望的结果

如何编写聚合管道以使返回的结果看起来像这样?

[
    {
        customer_id: 1,
        name: "Jim Smith",
        email: "[email protected]"
        orders: [
            {
                order_id: 1,
                items: [
                    {
                        name: "Foo",
                        price: 4.99
                    },
                    {
                        name: "Bar",
                        price: 17.99
                    }
                ]
            },
            {
                order_id: 2,
                items: [
                    {
                        name: "baz",
                        price: 24.99
                    }
                ]
            }
        ]
    },
    {
        customer_id: 2,
        name: "Bob Jones",
        email: "[email protected]"
        orders: []
    }
]

使用进行嵌套查找使用管道查找,

  • $lookup with orders collection,
    • let,定义变量customer_id这是来自主集合的,要使用管道内访问此引用变量$$ like $$customer_id,
    • pipeline可以像我们在根级管道中一样添加管道阶段
    • $expr每当我们匹配内部字段时,它都需要表达式匹配条件,所以$$customer_id是在中声明的父集合字段let and $customer_id是子集合/当前集合的字段
  • $lookup with orderitems收藏
db.customers.aggregate([
  {
    $lookup: {
      from: "orders",
      let: { customer_id: "$customer_id" },
      pipeline: [
        { $match: { $expr: { $eq: ["$$customer_id", "$customer_id"] } } },
        {
          $lookup: {
            from: "orderitems",
            localField: "order_id",
            foreignField: "order_id",
            as: "items"
          }
        }
      ],
      as: "orders"
    }
  }
])

操场


Tip:

在 NoSQL 中,有几种连接被认为是不好的做法,我建议您是否可以将订单项添加到订单集合中作为数组,您可以为订单项保存一个连接过程,请参阅改进版本操场

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 MongoDB 聚合管道中执行嵌套“连接”(连接 3 个或更多集合)? 的相关文章

随机推荐