在MongoDB中,你可以使用聚合管道(aggregation pipeline)進行嵌套查詢。聚合管道是一系列的階段(stages),每個階段都會對數據進行某種操作。要在MongoDB中進行嵌套查詢,你可以使用$unwind
、$group
、$project
等階段來處理數據。
以下是一個簡單的例子,說明如何在MongoDB中使用聚合管道進行嵌套查詢:
假設我們有一個名為orders
的集合,其中包含以下文檔:
[
{
"_id": 1,
"customer_id": 1,
"items": [
{ "product_id": 1, "quantity": 2 },
{ "product_id": 2, "quantity": 1 }
]
},
{
"_id": 2,
"customer_id": 2,
"items": [
{ "product_id": 1, "quantity": 1 },
{ "product_id": 3, "quantity": 2 }
]
},
{
"_id": 3,
"customer_id": 1,
"items": [
{ "product_id": 2, "quantity": 3 },
{ "product_id": 4, "quantity": 1 }
]
}
]
現在,我們想要查詢每個客戶的總消費金額(每個產品的數量乘以其價格)。首先,我們需要知道每個產品的價格。假設我們有一個名為products
的集合,其中包含以下文檔:
[
{ "_id": 1, "name": "Product A", "price": 10 },
{ "_id": 2, "name": "Product B", "price": 20 },
{ "_id": 3, "name": "Product C", "price": 30 },
{ "_id": 4, "name": "Product D", "price": 40 }
]
我們可以使用以下聚合管道查詢來計算每個客戶的總消費金額:
db.orders.aggregate([
{
$lookup: {
from: "products",
localField: "items.product_id",
foreignField: "_id",
as: "product_info"
}
},
{
$unwind: "$items"
},
{
$unwind: "$product_info"
},
{
$addFields: {
"total_amount": { $multiply: ["$items.quantity", "$product_info.price"] }
}
},
{
$group: {
_id: "$customer_id",
total_spent: { $sum: "$total_amount" },
items: { $push: "$items" },
product_info: { $push: "$product_info" }
}
},
{
$project: {
_id: 0,
customer_id: "$_id",
total_spent: 1,
items: 1,
product_info: 1
}
}
])
這個查詢的步驟如下:
$lookup
階段將orders
集合與products
集合連接起來,以便獲取每個產品的價格。$unwind
階段將items
數組和product_info
數組拆分成多個文檔。$addFields
階段計算每個訂單項的總金額(數量乘以價格)。$group
階段按客戶ID對文檔進行分組,并計算每個客戶的總消費金額。$project
階段重新格式化輸出結果。查詢結果將如下所示:
[
{
"customer_id": 1,
"total_spent": 160,
"items": [
{ "product_id": 1, "quantity": 2 },
{ "product_id": 2, "quantity": 1 },
{ "product_id": 2, "quantity": 3 },
{ "product_id": 4, "quantity": 1 }
],
"product_info": [
{ "_id": 1, "name": "Product A", "price": 10 },
{ "_id": 2, "name": "Product B", "price": 20 },
{ "_id": 4, "name": "Product D", "price": 40 }
]
},
{
"customer_id": 2,
"total_spent": 90,
"items": [
{ "product_id": 1, "quantity": 1 },
{ "product_id": 3, "quantity": 2 }
],
"product_info": [
{ "_id": 1, "name": "Product A", "price": 10 },
{ "_id": 3, "name": "Product C", "price": 30 }
]
}
]