Home:ALL Converter>How to use $regex in mongodb aggregation query within $match

How to use $regex in mongodb aggregation query within $match

Ask Time:2013-04-27T20:41:08         Author:Amol M Kulkarni

Json Formatter

I am trying to use the $regex within $match, its not returning the matching documents.

db.collection('MyCollection', function (err, collection) {
  collection.aggregate([
    { $match: { 'Code': 'Value_01', 'Field2': { $regex: '/Value_2/g' } } },  
    { $project: {
        _id: 1,
        CodeNumber: '$Code',
        FieldName2: '$Field2'
      }
    }
  ], function (err, Result_doc) {
    console.log(Result_doc);
  }
});

Can anyone tell me where its going wrong or the correct syntax?


I even tried with replacing the

'Field2': { $regex: /Value_2/g }

Author:Amol M Kulkarni,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/16252208/how-to-use-regex-in-mongodb-aggregation-query-within-match
JohnnyHK :

As it says in the $regex docs you linked to, the two ways to do this are:\n\nField2: /Value_2/g\n\n\nOR\n\nField2: { $regex: 'Value_2', $options: 'g' }\n\n\nBut I also tried your second attempt of 'Field2': { $regex: /Value_2/g } and that worked as well.\n\nBTW, the g regex option doesn't make sense in this context as you just need one match anyway. Note that it isn't even listed in the $regex docs.",
2013-04-27T13:34:57
yy