以下是我的mongodb结构:
[{ _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 }]
好吧,我尝试过这样使用aggregation
,但我认为我弄错了:
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 } ]
关于如何进行聚合的任何帮助可能都很受欢迎,请不要假设模型有任何变化.
提前致谢!
$unwind
在分组之前需要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 }