如何在$ match的MongoDB聚合查询中使用$ regex

我想在$match使用$regex ,它不返回匹配的文件。

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

谁能告诉我哪里出错或正确的语法?


我什至尝试用replace

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

正如它在你链接到的$regex文档中所说的,两种方法是:

 Field2: /Value_2/g 

要么

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

但是我也尝试了第二次尝试'Field2': { $regex: /Value_2/g } ,那也是一样的。

顺便说一句, g正则expression式在这种情况下是没有意义的,因为无论如何你只需要一个匹配。 请注意,它甚至没有列在$regex文档中。

我得到它与以下代码工作:

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

使用console.dir(Value_match)将对象内容推送到控制台时,将打印出'/Value_2/'