Sales
的样本集合如下所示:
[
{
"brand_id": "A",
"price": 500
},
{
"brand_id": "A",
"price": 700
},
{
"brand_id": "B",
"price": 1500
},
{
"brand_id": "C",
"price": 100
},
{
"brand_id": "D",
"price": 400
},
{
"brand_id": "D",
"price": 600
},
{
"brand_id": "D",
"price": 200
}
]
这是我当前的解决方案:
const data = await Sales.aggregate([
{
$group: {
_id: "$brand_id",
total_sales: {
$sum: "$price"
},
records: {
$push: "$$ROOT"
}
}
},
{
$match: {
total_sales: {
$gt: 1000
}
}
},
{
$unwind: "$records"
},
{
$replaceWith: "$records"
}
])
我想做的是,从
Sales
集合中,我试图获取按brand_id分组的所有文档,并且每个品牌的总订单价值大于1000美元(阈值)。
但我有另一个名为
Brands
的集合,其中包含品牌 ID、品牌名称和阈值。
所以它会是这样的:
[
{
brand_id: 124,
brand_name: "abc",
threshold: 1000,
},
{
brand_id: 54,
brand_name: "hef",
threshold: 600,
},
{
brand_id: 80,
brand_name: "xyz",
threshold: 310,
}
]
问题是,我可以迭代
Brands
的文档并将阈值传递给聚合函数并每次调用它。但这似乎不是正确的方法。
我尝试用谷歌搜索类似的场景。但没找到。
我期望的输出与此类似:
[
"A":[
{
"_id": ObjectId("5a934e000102030405000000"),
"brand_id": "A",
"price": 500
},
{
"_id": ObjectId("5a934e000102030405000001"),
"brand_id": "A",
"price": 700
},
],
"B":[
{
"_id": ObjectId("5a934e000102030405000002"),
"brand_id": "B",
"price": 1500
},
],
"D":[
{
"_id": ObjectId("5a934e000102030405000004"),
"brand_id": "D",
"price": 400
},
{
"_id": ObjectId("5a934e000102030405000005"),
"brand_id": "D",
"price": 600
},
{
"_id": ObjectId("5a934e000102030405000006"),
"brand_id": "D",
"price": 200
}
]
]
我建议你从
$lookup
集合中的Brands
开始查找所有销售记录。对 $sum
结果使用 $lookup
即可获取总销售额,然后使用 $match
与 threshold
值
db.brands.aggregate([
{
"$lookup": {
"from": "sales",
"localField": "brand_id",
"foreignField": "brand_id",
"as": "salesLookup"
}
},
{
"$set": {
"total_sales": {
$sum: "$salesLookup.price"
}
}
},
{
"$match": {
$expr: {
$gte: [
"$total_sales",
"$threshold"
]
}
}
}
])