【问题标题】:How to use $regex in mongodb aggregation query within $match如何在 $match 内的 mongodb 聚合查询中使用 $regex
【发布时间】:2013-04-21 13:24:29
【问题描述】:

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

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


我什至尝试更换
'Field2': { $regex: /Value_2/g }

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

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

    Field2: /Value_2/g
    

    Field2: { $regex: 'Value_2', $options: 'g' }
    

    但我也尝试了您第二次尝试'Field2': { $regex: /Value_2/g },效果也不错。

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

    【讨论】:

    • $options 在我输入$regex:"<value>" 时未显示在$match 查询下。
    • 注意:全局选项不支持 MongoDB 正则表达式操作 (source)。
    【解决方案2】:

    我得到它使用以下代码:

    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);
      }
    });
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-22
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 2020-08-12
      • 2019-03-25
      • 2015-12-28
      • 1970-01-01
      相关资源
      最近更新 更多