Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 }
like image 944
Amol M Kulkarni Avatar asked Apr 27 '13 12:04

Amol M Kulkarni


People also ask

What can the $match aggregation stage be used for?

The $match stage of the pipeline can be used to filter documents so that only ones meeting certain criteria move on to the next stage. In this article, we'll discuss the $match stage in more detail and provide examples that illustrate how to perform match aggregation in MongoDB.

Can we use $and in aggregate MongoDB?

You can use $and with aggregation but you don't have to write it, and is implicit using different filters, in fact you can pipe those filters in case one of them needs a different solution.

What does $match do in MongoDB?

The MongoDB $match operator filters the documents to pass only those documents that match the specified condition(s) to the next pipeline stage.

What is $regex in MongoDB?

$regex. Provides regular expression capabilities for pattern matching strings in queries. MongoDB uses Perl compatible regular expressions (i.e. "PCRE" ) version 8.42 with UTF-8 support.


2 Answers

As it says in the $regex docs you linked to, the two ways to do this are:

Field2: /Value_2/g

OR

Field2: { $regex: 'Value_2', $options: 'g' }

But I also tried your second attempt of 'Field2': { $regex: /Value_2/g } and that worked as well.

BTW, 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.

like image 86
JohnnyHK Avatar answered Sep 23 '22 18:09

JohnnyHK


I got it working with the following code:

var Value_match = new RegExp('Value_2');

db.collection('MyCollection', function (err, collection) {

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

On pushing the object content to console using console.dir(Value_match) it prints out '/Value_2/'

like image 22
Amol M Kulkarni Avatar answered Sep 24 '22 18:09

Amol M Kulkarni