How to use $ regex in mongodb aggregation request in $ match

I am trying to use $regex in $match without returning the relevant 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 someone tell me where this is going wrong or the correct syntax?


I even tried with a replacement
 'Field2': { $regex: /Value_2/g } 
+9
source share
2 answers

As the $regex docs you are associated with say two ways to do this:

 Field2: /Value_2/g 

OR

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

But I also tried your second attempt at 'Field2': { $regex: /Value_2/g } , and it worked.

By the way, the g regex option does not make sense in this context, since you just need one match. Note that it is not even listed in the $regex docs.

+14
source

I started 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); } }); 

When you push the contents of an object to the console using console.dir(Value_match) it displays '/Value_2/'

+3
source

Source: https://habr.com/ru/post/943773/


All Articles