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

Amo*_*rni 14 mongodb node.js

我试图使用$regex内部$match,它不返回匹配的文件.

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);
  }
});
Run Code Online (Sandbox Code Playgroud)

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


我甚至试过更换了

'Field2': { $regex: /Value_2/g }
Run Code Online (Sandbox Code Playgroud)

Joh*_*yHK 20

正如$regex您在链接到的文档中所述,执行此操作的两种方法是:

Field2: /Value_2/g
Run Code Online (Sandbox Code Playgroud)

要么

Field2: { $regex: 'Value_2', $options: 'g' }
Run Code Online (Sandbox Code Playgroud)

但我也试过了你的第二次尝试,'Field2': { $regex: /Value_2/g }这也很有效.

顺便说一下,g正则表达式选项在这种情况下没有意义,因为你只需要一个匹配.请注意,它甚至没有在$regex文档中列出.


Amo*_*rni 6

我用下面的代码让它工作:

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);
  }
});
Run Code Online (Sandbox Code Playgroud)

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