For MongoDB 3.6 and newer:
100运算符允许在查询语言中使用聚合表达式,因此您可以利用101运算符判断字符串的长度,如下所示:
db.usercollection.find({
"name": { "$exists": true },
"$expr": { "$gt": [ { "$strLenCP": "$name" }, 40 ] }
})
For MongoDB 3.4 and newer:
您还可以将聚合框架与100管道操作符一起使用,它允许您使用101操作符处理逻辑条件,并使用特殊操作102"保留"逻辑条件为真的文档,或使用103"删除"条件为假的文档.
此操作类似于使用100管道 Select 集合中的字段,并创建一个新字段,该字段保存逻辑条件查询的结果,然后创建一个后续的101,只是102使用一个更高效的管道阶段.
至于逻辑条件,有String Aggregation Operators个可以使用101运算符来判断字符串的长度.如果长度是指定的值,那么这是一个真正的匹配,文档被"保留".否则它会被"修剪"并丢弃.
考虑运行下面的聚合操作来演示上面的概念:
db.usercollection.aggregate([
{ "$match": { "name": { "$exists": true } } },
{
"$redact": {
"$cond": [
{ "$gt": [ { "$strLenCP": "$name" }, 40] },
"$$KEEP",
"$$PRUNE"
]
}
},
{ "$limit": 2 }
])
如果使用$where
,请try 不带括号的查询:
db.usercollection.find({$where: "this.name.length > 40"}).limit(2);
更好的查询是判断字段是否存在,然后判断长度:
db.usercollection.find({name: {$type: 2}, $where: "this.name.length > 40"}).limit(2);
或者:
db.usercollection.find({name: {$exists: true}, $where: "this.name.length >
40"}).limit(2);
MongoDB在$where
个表达式和非$where
个查询语句可能使用索引之前判断非$where
个查询操作.更好的性能是将字符串的长度存储为另一个字段,然后可以对其进行索引或搜索;相比之下,申请$where
将慢得多.当您无法以任何其他方式构造数据时,或者当您处理
避免使用$where
运算符的另一种更快的方法是101运算符.考虑下面的模式搜索
db.usercollection.find({"name": {"$type": 2, "$regex": /^.{41,}$/}}).limit(2);
Note-从100开始:
如果该字段存在索引,则MongoDB与常规索引匹配
如果正则表达式以
此外,虽然/^a/, /^a.*/,
和/^a.*$/
相当