首页 > 其他 > 详细

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

时间:2020-01-03 13:04:50      阅读:106      评论:0      收藏:0      [点我收藏+]
工作中偶尔会根据字符串字段的长度来筛选一些数据,这时候可能会用到正则表达式,也可以用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 的速度快很多

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!