问题描述
我想从我的收藏中获取所有记录,这些记录在移动列中可能带有加号(+)连字符(-)和数字
所以我允许查询中的以下记录类型
+91-1234567890
+911234567890
1234567890
如果移动列匹配以上三种格式中的任何一种,则这些记录应显示
通过使用以下查询,我得到的结果为空
db.collection.aggregate([{“ $ match”:{mobile:{$ regex:'^ [+]?(\ d-?){6,15} \ d $'}}}},{$ group:{_ id:null,count:{$ sum:1}}}]))
解决方法
您必须使用\\
来转义特殊字符“ +”和“-”db.collection.aggregate([
{
"$match": {
mobile: {
$regex: "^(\\+[0-9]{1,5}\\-|\\+[0-9]{1,5})?([0-9]{10})$"
}
}
},{
$group: {
_id: null,count: {
$sum: 1
}
}
}
])