Mongoose group and count

蓝咒 提交于 2020-06-25 00:54:07

问题


Below is my mongodb structure:

[{
    _id: '111',
    items: [{
        productId: '123'
    }]
}, {
    _id: '222',
    items: [{
        productId: '123'
    }, {
        productId: '456'
    }]
}, {
    _id: '333',
    items: [{
        productId: '123'
    }, {
        productId: '456'
    }, {
        productId: '789'
    }]
}]

And I expect to group and count productId so that the result to be:

[{
    productId: '123',
    count: 3
}, {
    productId: '456',
    count: 2
}, {
    productId: '789',
    count: 1
}]

Well, I tried using aggregation like this, but I think I got it wrong:

const aggregatorOpts = [{
  $group: {
    _id: "$items.productId",
    count: { $sum: 1 }
  }
}]

Model.aggregate(aggregatorOpts).exec()

I got:

result [
  { _id: [ '123' ], count: 1 },
  { _id: [ '123', '456' ], count: 1 },
  { _id: [ '123', '456', '789' ], count: 1 }
]

Any help regarding how to do the aggregation probably is appreciated, and please don't assume any change in the model.

Thanks in advance!


回答1:


You need to $unwind items array before grouping :

const aggregatorOpts = [{
        $unwind: "$items"
    },
    {
        $group: {
            _id: "$items.productId",
            count: { $sum: 1 }
        }
    }
]

Model.aggregate(aggregatorOpts).exec()

which gives :

{ "_id" : "789", "count" : 1 }
{ "_id" : "456", "count" : 2 }
{ "_id" : "123", "count" : 3 }



回答2:


Try this one.

    Model.aggregate([
        {
            $group: {
               _id: '$items.productId',
                points: {$count: '$items'}
           }
       }
     ]);

This should work.



来源:https://stackoverflow.com/questions/41791015/mongoose-group-and-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!