工作中偶爾會根據字符串字段的長度來篩選一些數據,這時候可能會用到正則表達式,也可以用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 的速度快很多