node.js 如何在 $match 内的 mongodb 聚合查询中使用 $regex

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16252208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:20:03  来源:igfitidea点击:

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

node.jsmongodb

提问by Amol M Kulkarni

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

我正在尝试使用$regexinside $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);
  }
});

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

谁能告诉我哪里出了问题或正确的语法?



我什至尝试更换

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

回答by JohnnyHK

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

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

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.

但我也尝试了你的第二次尝试,结果'Field2': { $regex: /Value_2/g }也很好。

BTW, the gregex option doesn't make sense in this context as you just need one match anyway. Note that it isn't even listed in the $regexdocs.

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

回答by Amol M Kulkarni

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/'

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