如何在$ match中的mongodb聚合查询中使用$ regex [英] How to use $regex in mongodb aggregation query within $match

查看:513
本文介绍了如何在$ match中的mongodb聚合查询中使用$ regex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 $regex ="http://docs.mongodb.org/manual/reference/aggregation/#stage._S_match" rel ="noreferrer"> $match ,它不返回匹配的文档.

I am trying to use the $regex within $match, its not returning the matching 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 anyone tell me where its going wrong or the correct syntax?


I even tried with replacing the

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

推荐答案

正如您链接到的$regex文档中所说,实现此目的的两种方法是:

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

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.

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

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.

这篇关于如何在$ match中的mongodb聚合查询中使用$ regex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆