gpt4 book ai didi

mongodb - 如何在 MongoDB 聚合管道中执行嵌套 "joins"(加入 3 个或更多集合)?

转载 作者:行者123 更新时间:2023-12-04 08:09:54 26 4
gpt4 key购买 nike

假设我们在 MongoDB 中有 3 个假设集合:customersordersorderItems

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

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

客户

[
{
customer_id: 1,
name: "Jim Smith",
email: "jim.smith@example.com"
},
{
customer_id: 2,
name: "Bob Jones",
email: "bob.jones@example.com"
}
]

订单

[
{
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: "jim.smith@example.com"
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: "bob.jones@example.com"
orders: []
}
]

最佳答案

使用 lookup with pipeline 进行嵌套查找,

  • $lookuporders 集合,
    • let,定义来自主集合的变量 customer_id,使用 $$$ 访问管道内的这个引用变量$customer_id,
    • pipeline 可以像我们在根级管道中一样添加管道阶段
    • $expr 每当我们匹配内部字段时,它需要表达式匹配条件,所以 $$customer_id 是在 let 中声明的父集合字段,并且$customer_id 是子集合/当前集合的字段
  • $lookuporderitems 集合
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"
}
}
])

Playground


Tip:

Several joins considered as bad practice in NoSQL, I would suggest if you could add your order items in orders collection as array, you can save one join process for orderitems, see improved version in playground

关于mongodb - 如何在 MongoDB 聚合管道中执行嵌套 "joins"(加入 3 个或更多集合)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66031972/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com