Mongoose Group and Account

The following 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 assume productIdthat the result is:

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

Well, I tried using aggregationlike this, but I think I was 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 aggregation is likely to be appreciated, and please do not accept any changes to the model.

Thanks in advance!

+4
source share
2 answers

Before grouping you need an $unwindarray of elements:

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 }
+4
source

Try it.

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

That should work.

0
source

Source: https://habr.com/ru/post/1667475/


All Articles