Mongodb-$strLenCP的使用
之前在使用SQL时,我们经常会使用到Len()函数来返回文本字段中值的长度。那Mongodb是否有这样的操作呢,在version 3.4增加了此功能$strLenCP 如:有一个客户购买商品信息集合orderdetail
{"_id": ObjectId("5821757bf28fbb3e3516eeaa"), "memid" : "f5869354", "orderno" : "s00023","productno":"20206539", "comment":"这个平底锅太好用了,性价比高","telephone" :"18385669845"} {"_id": ObjectId("5821776ff28fbb3e3516eeab"), "memid" : "daisy", "orderno" : "s04567", "productno":"20225699","address":"comment","衣服穿起来很舒服好评" :"18855448645"} {"_id": ObjectId("5821829ef28fbb3e3516eeac"), "memid" : "lucy", "orderno" : "s08795", "productno":"20256339","address":"comment","还行" :"13869669585"} {"_id": ObjectId("582182b0f28fbb3e3516eead"), "memid" : "c5633256", "orderno" : "s45689","productno":"20285639","address":"comment","不好用,不建议买" :"13699869588"}
我们想统计客户评论信息的长度,操作如下:
db.orderdetail.aggregate( [ { $project: { "_id":0, "orderno": 1, "productno":1, "comlength": { $strLenCP: "$comment" } } } ] ) {"orderno" : "s00023", "productno":"20206539", "comlength":14} {"orderno" : "s04567", "productno":"20225699", "comlength":10} {"orderno" : "s08795", "productno":"20256339", "comlength":2} {"orderno" : "s45689", "productno":"20285639", "comlength":8}
这样就可以得出长度,也可以通过这个length继续后面的分析
比如说想看看评论长度大于10的商品
db.orderdetail.aggregate( [ { $project: { "_id":0, "orderno": 1, "productno":1, "comlength": { $strLenCP: "$comment" } } }, { $match:{comlength:{$gt:10}} } ] ) {"orderno" : "s00023", "productno":"20206539", "comlength":14}
需要注意一点的是$strLenCP和$strLenBytes功能相近,但是在统计字符的时候有区别
$strLenByte会区分字符类型,比如:汉字会默认为3个字节,特殊字符如€为3个字节,λ为2个字节,é也为2个字节
当然想要实现上述功能,还可以通过$where来实现,但是多数情况下都避免使用$where查询,比常规查询慢很多,每个文档都要从BSON转换成JavaScript对象,然后通过$where表达式来运行,而且不能使用索引。这样看来通过管道操作来实现会是不错的选择。
转载地址:http://forum.foxera.com/mongodb/topic/1619/mongodb-strlencp%E7%9A%84%E4%BD%BF%E7%94%A8