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