我正在尝试在 $regex ="docs.mongodb/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/gOR
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
发布评论