Want to sum bonuses by all clients and get qty of clients via 1 query (and hope only 1 request) that look like this:
const pipeline = [
{
facet: {
bonusesResult: [
{
$match: {...},
},
{
$group: {
_id: null,
total: {
$sum: '$bonuses',
},
},
},
],
clientQtyResult: [{ $group: { _id: '$client' } }, { $count: 'qty' }],
},
},
];
const result = await query.equalTo('merchant', merchant).aggregate(pipeline);
The first part works fine, counts all bonuses by all client (only 2 clients in the test DB), but does not count clients:
bonusesResult = { _id: null, total: 153 }
clientQtyResult = { qty: 1 }
Just wann’t group by client
field, if I leave only group
(w/o count
):
clientQtyResult: [{ $group: { _id: '$client' } }]
it will return: clientQtyResult = { _id: null }
Without facet
it works perfectly with
const numberOfClientsPipeline = [
{ group: { objectId: '$client' } },
{ count: 'numberOfClients' },
];
So I had had to make 2 queries. That is not so critical (at least now) but I interest for the future why I can’t make to group by field inside facet
.