joselegit
joselegit

Reputation: 533

mongoose aggregate match not working with regex

I need to find some records using regex. When the parameter value ends in 0 the result is empty, but when the last character is different from zero (1 - 9) the query works fine.

Invoice.aggregate([{
  '$lookup': {
    'from': 'clients',
    'localField': 'client',
    'foreignField': '_id',
    'as': 'client'
  }
}, {
  '$unwind': '$client'
}, {
  '$lookup': {
    'from': 'employees',
    'localField': 'sold_by',
    'foreignField': '_id',
    'as': 'sold_by'
  }
}, {
  '$unwind': '$sold_by'
}, {
  '$lookup': {
    'from': 'payment_types',
    'localField': 'payment_type',
    'foreignField': '_id',
    'as': 'payment_type'
  }
}, {
  '$unwind': '$payment_type'
}, {
  '$lookup': {
    'from': 'payments',
    'localField': 'payments.payment',
    'foreignField': '_id',
    'as': 'payment'
  }
}, {
  '$unwind': '$payment'
}, {
  $match: {
        'invoice': {
      $regex: /2490/i
    }
  }
}])

When the query works the result exclude all the records that ends in 0. I try using the regex in this other way

"$match" : {
                "invoice" : /^.*2490.*$/i
            }

and the result is the same.

I use regex in other String fields and work fine only in this field doesn't work. the field store values like this

{
'000-0000-2490',
'000-0000-2491',
'000-0000-2492'
}

Upvotes: 1

Views: 3393

Answers (1)

Ashh
Ashh

Reputation: 46451

Actually - is a special character and will not work with the regular expression syntax.

Instead you need to use $regex operator here

{ "$match" : { "invoice" : { "$regex": "000-0000-2490", "$options": "i" } } }

Upvotes: 2

Related Questions