Basim Hennawi
Basim Hennawi

Reputation: 2721

Mongoose group and count

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!

Upvotes: 13

Views: 27382

Answers (2)

Bertrand Martel
Bertrand Martel

Reputation: 45493

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 }

Upvotes: 26

PayPal_Kartik
PayPal_Kartik

Reputation: 226

Try this one.

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

This should work.

Upvotes: 0

Related Questions