字段的数据类型是字符串。我想获取字段名称字符长度大于40的数据。
我尝试了这些查询,但返回错误。 1.
db.usercollection.find(
{$where: "(this.name.length > 40)"}
).limit(2);
output :error: {
"$err" : "TypeError: Cannot read property 'length' of undefined near '40)' ",
"code" : 16722
}
这适用于 2.4.9 但我的版本是 2.6.5
最佳答案
对于 MongoDB 3.6 及更高版本:
$expr
运算符允许在查询语言中使用聚合表达式,因此您可以利用 $strLenCP
运算符检查字符串的长度如下:
db.usercollection.find({
name: { $exists: true },
$expr: { $gt: [{ $strLenCP: '$name' }, 40] }
})
对于 MongoDB 3.4 及更高版本:
您还可以将聚合框架与 $redact
一起使用允许您使用 $cond
处理逻辑条件的管道运算符运算符并使用特殊运算 $$KEEP
“保留”逻辑条件为真或 $$PRUNE
的文档“删除”条件为假的文档。
此操作类似于使用 $project
管道选择集合中的字段并创建一个新字段来保存逻辑条件查询的结果,然后是后续的 $match
, 除了 $redact
使用更高效的单个流水线阶段。
至于逻辑条件,有String Aggregation Operators您可以使用$strLenCP
运算符来检查字符串的长度。如果长度为$gt
一个指定的值,那么这是一个真正的匹配并且文档被“保留”。否则,它会被“修剪”并丢弃。
考虑运行以下展示上述概念的聚合操作:
db.usercollection.aggregate([
{ $match: { name: { $exists: true } } },
{ $redact: {
$cond: [
{ $gt: [ { $strLenCP: "$name" }, 40] },
"$$KEEP",
"$$PRUNE"
]
} },
{ $limit: 2 }
])
如果使用 $where
,请尝试不带括号的查询:
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
与此相比会慢得多。建议使用 JavaScript 表达式和 $where
当您无法以任何其他方式构建数据时,或者当您正在处理
一小部分数据。
另一种更快的方法,避免使用 $where
运算符是 $regex
运算符(operator)。考虑以下搜索模式
db.usercollection.find({"name": {"$type": 2, "$regex": /^.{41,}$/}}).limit(2);
注意 - 来自 docs :
If an index exists for the field, then MongoDB matches the regular expression against the values in the index, which can be faster than a collection scan. Further optimization can occur if the regular expression is a “prefix expression”, which means that all potential matches start with the same string. This allows MongoDB to construct a “range” from that prefix and only match against those values from the index that fall within that range.
A regular expression is a “prefix expression” if it starts with a caret
(^)
or a left anchor(\A)
, followed by a string of simple symbols. For example, the regex/^abc.*/
will be optimized by matching only against the values from the index that start withabc
.Additionally, while
/^a/, /^a.*/,
and/^a.*$/
match equivalent strings, they have different performance characteristics. All of these expressions use an index if an appropriate index exists; however,/^a.*/
, and/^a.*$/
are slower./^a/
can stop scanning after matching the prefix.
关于mongodb - mongoDB中的字符串字段值长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29577713/