我正在进行一些聚合,以获取有关类别中有多少产品的统计信息。
经过一些管道处理后,我明白了:
[
{
topCategory: "Computer",
mainCategory: "Stationary"
},
{
topCategory: "Computer",
mainCategory: "Laptop"
},
{
topCategory: "Computer",
mainCategory: "Stationary"
},
{
topCategory: "Computer",
mainCategory: "Stationary"
},
]
想要的输出:
[
{
name: "Computer",
count: 4,
mainCategories: [
{
name: "Laptop",
count: 2
},
{
name: "Stationary",
count: 2
}
]
}
]
到目前为止我的查询:
let query = mongoose.model('Product').aggregate([
{
$match: {
project: mongoose.Types.ObjectId(req.params.projectId)
}
},
{ $project: {
_id: 0,
topCategory: '$category.top',
mainCategory: '$category.main',
}
},
]);
我知道我需要将 $group
与 $sum
结合使用。我尝试了不同的方法,但无法使其工作。
最佳答案
在这种情况下,您应该首先按 mainCategory
分组,然后按 topCategory
分组,如下所示
db.collection.aggregate({
$group: {
_id: "$mainCategory",
"count": {
$sum: 1
},
"data": {
"$push": "$$ROOT"
}
}
}, {
"$unwind": "$data"
}, {
"$group": {
"_id": "$data.topCategory",
"count": {
"$sum": 1
},
"mainCategories": {
"$addToSet": {
"name": "$_id",
"count": "$count"
}
}
}
}).pretty()
关于Mongodb,$group 中项目的总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41649807/