MongoDB 字符串值長度條件查詢


在實際項目中常常會有根據字段值長度大小進行限制查詢,例如查詢商品名稱過長或過短的商品信息,具體的實現方式可能有多種,在此記錄常見的兩種實現

 

  • 使用 $where 查詢(性能稍遜一些)

1
2
3
4
5
//查詢商品名稱長度大於25個字符的商品
db.item.find({item_name:{$exists: true },$where: "(this.item_name.length > 25)" }).limit(5)
 
//查詢商品名稱長度小於5個字符的商品
db.item.find({$where: "this.item_name.length < 5" }).limit(5)

 

  • 使用正則表達式查詢(性能比$where 高)

1
2
3
4
5
//查詢商品名稱長度大於25個字符的商品
db.item.find({ "item_name" : { "$exists" true "$regex" : /^.{25,}$/}}).limit(5)
 
//查詢商品名稱長度小於5個字符的商品
db.item.find({ "item_name" : { "$regex" : /^.{0,5}$/}}).limit(5)

 

Java 使用 Spring data mongodb:

1
2
3
4
5
String pattern = String.format( "^.{%s,}$" , overlength);
Criteria criteria = Criteria.where( "item_name" ).regex(pattern,  "m" );
 
Query query =  new  Query(criteria);
mongoTemplate.find(query, Item. class )

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM