【问题标题】:Fetch Data with regex match in mongoDB在 mongoDB 中使用正则表达式匹配获取数据
【发布时间】:2020-10-13 12:42:38
【问题描述】:

我想从我的集合中获取所有可能在移动列中有加号(+)连字符(-)和数字的记录

所以我允许从我的查询中输入以下类型的记录

+91-1234567890
+911234567890
1234567890

如果移动列匹配以上三种格式中的任何一种,则应显示这些记录

通过使用以下查询,我得到空结果

db.collection.aggregate([{"$match":{mobile:{$regex:'^[+]?(\d-?){6,15}\d$'}}},{$组:{_id:null,count:{$sum:1}}}]);

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    您必须使用 \\ 转义特殊字符“+”和“-”

    db.collection.aggregate([
      {
        "$match": {
          mobile: {
            $regex: "^(\\+[0-9]{1,5}\\-|\\+[0-9]{1,5})?([0-9]{10})$"
          }
        }
      },
      {
        $group: {
          _id: null,
          count: {
            $sum: 1
          }
        }
      }
    ])
    

    See the working example in MongoDB playground

    【讨论】:

      猜你喜欢
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      相关资源
      最近更新 更多