Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 373
Basim Hennawi Avatar asked Jan 22 '17 12:01

Basim Hennawi


People also ask

How does a mongoose count data?

Mongoose | countDocuments() Function The countDocuments() function is used to count the number of documents that match the filter in a database collection.

What is $Group in mongoose?

Definition. $group. The $group stage separates documents into groups according to a "group key". The output is one document for each unique group key. A group key is often a field, or group of fields.

Can we use count with aggregate function in MongoDB?

MongoDB $count AggregationThe MongoDB $count operator allows us to pass a document to the next phase of the aggregation pipeline that contains a count of the documents. There a couple of important things to note about this syntax: First, we invoke the $count operator and then specify the string.


1 Answers

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 }
like image 62
Bertrand Martel Avatar answered Oct 07 '22 04:10

Bertrand Martel