Can't group by field inside facet

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.

What is client, a Pointer? If yes, try with $_p_client instead of $client

Yes, pointer. Thanks I’ll try it today. So sorry that I wasting your time distracting for nothing, may be I can read about such things somewhere?

UPD. Yee, it’s working. Thanks a lot!

No problem. Unfortunately it is not documented. _p_client is the way pointer fields are stored inside MongoDB. createdAt should work also for facet, but clearly the conversion was not implemented for facet. Feel free to open a ticket in the repository.

Could you explain please how I must use match by pointer inside pipeline?
I have code like from my previouse question, and at once found that not only comparing by date does not work. equalTo also had no effect. I guess that I need move equalTo to date comparing to match stage inside pipeline, but I don’t know what is right syntax must be.

Because for date comparing { match: { createdAt: { $gt: DateObj } } } work fine by analogy I tried with { match: { pointerFieldName: { $eq: pointerObj } } } but without success. May be there are own tricks for that?

Pointer object must be string. İt’s should be

ClassName$objectid for example for the user class

_User$FgY56FrtHj

Thanks a lot, it’s working! At first I forget remove _ before my custom ClassName :), but then all was ok. Without your advice I never would’ve guessed about such syntax, earlier I only tried simple objectId.

No problem. _ is only used in system classes such as session installation or schema. Normal classes doesn’t have that. Glad you figured out