我對 Mongo 很陌生。我有兩個集合,如下所示。
訂單收集
[
{
id: 1,
price: 249,
store: 1,
status: true
},
{
id: 2,
price: 230,
store: 1,
status: true
},
{
id: 3,
price: 240,
store: 1,
status: true
},
{
id: 4,
price: 100,
store: 2,
status: true
},
{
id: 5,
price: 150,
store: 2,
status: true
},
{
id: 6,
price: 500,
store: 3,
status: true
},
{
id: 7,
price: 70,
store: 4,
status: true
},
]
商店收藏
[
{
id: 1,
name: "Store A",
status: true
},
{
id: 2,
name: "Store B",
status: true
},
{
id: 3,
name: "Store C",
status: true
},
{
id: 4,
name: "Store D",
status: false
}
]
如何從訂單串列中找到排名靠前的商店,這應該基于每個商店的總銷售額。
我已經嘗試過以下
db.order.aggregate([
{
"$match": {
status: true
}
},
{
"$group": {
"_id": "$store",
"totalSale": {
"$sum": "$price"
}
}
},
{
$sort: {
totoalSale: -1
}
}
])
我從上面的片段中得到了商店的排序串列。但我想添加商店詳細資訊以及總銷售額。
更多資訊:https : //mongoplayground.net/p/V3UH1r6YRnS
預期產出
[
{
id: 1,
name: "Store A",
status: true,
totalSale: 719
},
{
id: 1,
name: "Store c",
status: true,
totalSale: 500
},
{
_id: 2,
id: 1,
name: "Store B",
status: true,
totalSale: 250
},
{
_id: 4,
name: "Store D",
status: true,
totalSale: 70
}
]
uj5u.com熱心網友回復:
$lookup-store集合加入order集合并生成新欄位store_orders。$set-order使用status: truefrom過濾store_orders。$set- 的totalSale欄位總和store_orders.price。$sort- 按totalSale降序排序。$unset- 洗掉store_orders欄位。
db.store.aggregate([
{
$lookup: {
from: "order",
localField: "id",
foreignField: "store",
as: "store_orders"
}
},
{
$set: {
"store_orders": {
$filter: {
input: "$store_orders",
as: "order",
cond: {
$eq: [
"$$order.status",
true
]
}
}
}
}
},
{
$set: {
"totalSale": {
"$sum": "$store_orders.price"
}
}
},
{
$sort: {
totalSale: -1
}
},
{
$unset: "store_orders"
}
])
示例 Mongo Playground
uj5u.com熱心網友回復:
您可以從開始store收藏,$lookup在order收藏,$sum的totalSales,然后纏斗到您的預計形式
db.store.aggregate([
{
"$lookup": {
"from": "order",
let: {
id: "$id"
},
pipeline: [
{
$match: {
$expr: {
$eq: [
"$$id",
"$store"
]
}
}
},
{
$group: {
_id: null,
totalSale: {
$sum: "$price"
}
}
}
],
"as": "totalSale"
}
},
{
$unwind: "$totalSale"
},
{
$addFields: {
totalSale: "$totalSale.totalSale"
}
},
{
$sort: {
totalSale: -1
}
}
])
這里是Mongo 游樂場供您參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/348837.html
標籤:MongoDB 猫鼬 mongodb-查询 聚合框架
