Node.js 猫鼬群与计数
下面是我的mongodb结构:Node.js 猫鼬群与计数,node.js,mongodb,mongoose,aggregation-framework,Node.js,Mongodb,Mongoose,Aggregation Framework,下面是我的mongodb结构: [{ _id: '111', items: [{ productId: '123' }] }, { _id: '222', items: [{ productId: '123' }, { productId: '456' }] }, { _id: '333', items: [{ productId: '123' }, {
[{
_id: '111',
items: [{
productId: '123'
}]
}, {
_id: '222',
items: [{
productId: '123'
}, {
productId: '456'
}]
}, {
_id: '333',
items: [{
productId: '123'
}, {
productId: '456'
}, {
productId: '789'
}]
}]
我希望对productId
进行分组和计数,结果如下:
[{
productId: '123',
count: 3
}, {
productId: '456',
count: 2
}, {
productId: '789',
count: 1
}]
嗯,我试着像这样使用
聚合
,但我想我弄错了:
const aggregatorOpts = [{
$group: {
_id: "$items.productId",
count: { $sum: 1 }
}
}]
Model.aggregate(aggregatorOpts).exec()
我得到:
result [
{ _id: [ '123' ], count: 1 },
{ _id: [ '123', '456' ], count: 1 },
{ _id: [ '123', '456', '789' ], count: 1 }
]
对于如何进行聚合的任何帮助,我们都将不胜感激,请不要假设模型中有任何更改
提前谢谢 试试这个
Model.aggregate([
{
$group: {
_id: '$items.productId',
points: {$count: '$items'}
}
}
]);
这应该是可行的。在分组之前,您需要先创建项目数组:
const aggregatorOpts = [{
$unwind: "$items"
},
{
$group: {
_id: "$items.productId",
count: { $sum: 1 }
}
}
]
Model.aggregate(aggregatorOpts).exec()
其中:
{ "_id" : "789", "count" : 1 }
{ "_id" : "456", "count" : 2 }
{ "_id" : "123", "count" : 3 }
未知组运算符
$count
。信息技术可能是的语法错误。请尝试将“$count:'$items”更改为$sum:1”,这将使我们返回初始点。@Bertrand的答案已经解决了这个问题。感谢您的帮助!