Home > other >  Mongoose facet filter with $match and $near
Mongoose facet filter with $match and $near

Time:09-22

I try to filter collection using $match filter and $near filter with an aggregation (to know how many items match the query)

Here is my function

this.usersModel.aggregate([
      {
        $match: {
          practices: 'practice1',
          status: 'new',
        },
        $geoNear: {
          near: { type: 'Point', coordinates: ['43.48', '5.34'] },
          key: 'addresses',
        },
      },
      {
        $facet: {
          metadata: [
            {
              $group: {
                _id: null,
                total: { $sum: 1 },
              },
            },
          ],
          data: [{ $sort: sort }, { $skip: skip }, { $limit: limit }],
        },
      },
    ]);

For informations 'Addresses' is a geoSpacial field with index.

When I run this function with mongoose, I get this error

Arguments must be aggregate pipeline operators

CodePudding user response:

This is your problem:

{
    $match: {
        practices: 'practice1',
            status: 'new',
    },
    $geoNear: {
        near: { type: 'Point', coordinates: ['43.48', '5.34'] },
        key: 'addresses',
    },
},

I'm not sure if it's a mistake or not but you're basically merging 2 pipeline operators into 1, that's why the parser fails to understand what's going on.

Change it into:

{
    $geoNear: {
        near: { type: 'Point', coordinates: ['43.48', '5.34'] },
        key: 'addresses',
    },
},
{
    $match: {
        practices: 'practice1',
            status: 'new',
    }
},
... rest of pipeline
  • Related