在MongoDB中,你可以使用聚合管道(aggregation pipeline)進(jìn)行嵌套查詢。聚合管道是一系列的階段(stages),每個(gè)階段都會(huì)對數(shù)據(jù)進(jìn)行某種操作。要在MongoDB中進(jìn)行嵌套查詢,你可以使用$unwind
、$group
、$project
等階段來處理數(shù)據(jù)。
以下是一個(gè)簡單的例子,說明如何在MongoDB中使用聚合管道進(jìn)行嵌套查詢:
假設(shè)我們有一個(gè)名為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 }
]
}
]
現(xiàn)在,我們想要查詢每個(gè)客戶的總消費(fèi)金額(每個(gè)產(chǎn)品的數(shù)量乘以其價(jià)格)。首先,我們需要知道每個(gè)產(chǎn)品的價(jià)格。假設(shè)我們有一個(gè)名為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 }
]
我們可以使用以下聚合管道查詢來計(jì)算每個(gè)客戶的總消費(fèi)金額:
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
}
}
])
這個(gè)查詢的步驟如下:
$lookup
階段將orders
集合與products
集合連接起來,以便獲取每個(gè)產(chǎn)品的價(jià)格。$unwind
階段將items
數(shù)組和product_info
數(shù)組拆分成多個(gè)文檔。$addFields
階段計(jì)算每個(gè)訂單項(xiàng)的總金額(數(shù)量乘以價(jià)格)。$group
階段按客戶ID對文檔進(jìn)行分組,并計(jì)算每個(gè)客戶的總消費(fèi)金額。$project
階段重新格式化輸出結(jié)果。查詢結(jié)果將如下所示:
[
{
"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 }
]
}
]