到目前为止来自管道的结果:
[
{
catId: 'A1',
categories: [
{
name: 'Monitors',
section: 99
},
{
name: 'Monitors',
section: 99
},
{
name: 'Monitors',
section: 98
}
]
}
]
我已经用cat id对其进行了分组,并使用$ push来填充类别数组。
我还要对类别数组进行分组
[
{
catId: 'A1',
categories: [
{
name: 'Monitors',
section: 99,
count: 2
}
{
name: 'Monitors',
section: 98,
count: 1
}
]
}
]
我还没有找到任何关于如何在数组上执行$ group的示例。
到目前为止我的查询:
let query = mongoose.model('categories').aggregate([
{
$group: {
_id: {catId: '$catId'},
categories: {$push: {name: "$name", section: "$section"}}
}
},
{
$project: {
catId: '$_id.catId',
categories: 1,
_id: 0,
}
}
]);
答案 0 :(得分:2)
所以不要做你正在做的事情,先做另一个$group
:
let query = mongoose.model('categories').aggregate([
{ $group: {
_id: { catId: "$catId", name: "$name", section: "$section" },
count: { $sum: 1 }
}},
{ $group: {
_id: '$_id.catId',
categories: {
$push: {
name: "$_id.name",
section: "$_id.section",
count: "$count"
}
}
}}
]);
还习惯使用_id
作为输出的主键,因为添加额外的$project
阶段实际上只是浪费CPU和I / O.字段名称就是它们,$group
阶段的表现非常好。