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

时间:2022-07-19 15:45:15

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

我试图在$ 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);
  }
});

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

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


I even tried with replacing the

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

2 个解决方案

#1


14  

As it says in the $regex docs 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 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.

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

#2


3  

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

#1


14  

As it says in the $regex docs 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 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.

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

#2


3  

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