Mongo指定字符串长度查找数据的两种方法

工作中偶尔会根据字符串字段的长度来筛选一些数据,这时候可能会用到正则表达式,也可以用mongodb的$where,正则表达式在不同的语言中,正确写法又有所差异,特此记录一下。  

假如查找comment字段字符串长度大于10的数据,mongodb命令行写法如下:

$where写法:

find({"comment":{"$exists":true},"$where":"this.comment.length>10"})

正则表达式写法:

find({"comment":{"$regex":/^.{10,}$/}})

go语言中写法如下:

$where写法:
collection.Find(bson.M{"comment": bson.M{"$exists": true}, "$where": "this.comment.length > 10"})
正则表达式写法:
collection.Find(bson.M{"comment": bson.M{"$exists": true, "$regex": bson.RegEx{`^.{10,}$`, ""}}})

其他条件正则:
^.{n,m}$ n <= 长度 <= m
^.{n}$ 长度 = n

这个长度是字符的长度,比如"正则表达式"长度就是5

上面的内容转自https://www.ucloud.cn/yun/19509.html

鄙人试过40w的数据查询,正则的性能比$where 的速度快很多

原文地址:https://www.cnblogs.com/lfm601508022/p/12144240.html