1

I am using MongoDB aggregation pipeline to filter my data based on a name. But when I run the code below, it shows an error which I have not been able to crack.

I have a model Employee with name, gender, department, and age as their fields.

    filter = {};
    filter.$and = [];

    filter.$and.push( {
            name: { $regex: '(?i)' + fname + '.*' }
        }

    Employee.aggregate([
    {
        $match: 
        {
            $expr: filter
        }
    }
    )].exec((err, result) => {
    if (err) res.json({ success: false, msg: err });
    else {
        res.json(result);
    }
});

It gives an error:

{
  "success":false,
  "msg":
       {
        "ok":0,
        "errmsg":"Unrecognized expression '$regex'",
        "code":168,
        "codeName":"InvalidPipelineOperator",
        "name":"MongoError"
       }
 }
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Monu Chaudhary
  • 360
  • 3
  • 9
  • You cannot us a `$regex` or ANY "query operator" within an `$expr` as that is for "aggregation operators" only. Anyway you actually mean just `{ "$match": { "name": { $regex: '(?i)' + fname + '.*' } } }` Or indeed `{ "$match": { "name": { $regex: 'fname' $options: 'i' } } }` since I don't think you understand the "case insensitve" option properly. The `?i` is for a different purpose that what you are attempting. – Neil Lunn Apr 01 '19 at 11:10
  • See also [`$regex`](https://docs.mongodb.com/manual/reference/operator/query/regex/). And of course you almost never actually need to use the `$and` operator. For instance { "field": { "$gt": 1, "$lt": 3 } }` is actually an AND expression equilavent to `{ "$and": [{ "field": { "$gt": 1 } },{ "field": { "$lt": 3 } }] }`, but infinitely cleaner and easier to read. – Neil Lunn Apr 01 '19 at 11:13

0 Answers0