您如何查询 mongodb 以查找特定字符串/文本字段的长度?
您如何找到查询集的最大长度?
不幸的是,聚合框架不支持“len”运算符在您进行查询时自动将字符串转换为其长度。所以你必须在你自己的代码中解决这个问题。你可以
这些方法之间的区别在于,第一个在数据库上运行,而后者在您的应用程序服务器上运行。我会推荐后一种选择,因为 MapReduce 使用起来可能非常缓慢且麻烦。
天空才是极限!不,实际上它是16 MB针对mongodb. 这可以是记录中字符串的最大长度。
为了找到查询集中的最大长度,您可以执行以下工作:
开始Mongo 3.4,$strLenCP聚合运算符可用于获取字符串的长度:
// { a: "Hello World" }
// { a: "42" }
// { a: "Hello World!" }
db.collection.aggregate([{ $addFields: { length: { $strLenCP: "$a" } } }])
// { a: "Hello World", length: 11 }
// { a: "42", length: 2 }
// { a: "Hello World!", length: 12 }
为了通过$group/$max阶段从所有文档中获取最大长度:
db.collection.aggregate([
{ $group: { _id: null, longest: { $max: { $strLenCP: "$a" } } } }
])
// { "_id" : null, longest: 12 }
如何改用正则表达式。
> db.apps.find({$where:"(this.id.length gt 6) && (this.id.length lt 15)" }).count();
2548
> db.apps.find({$where:" (this.id.length gt 6) && (this.id.length lt 15) " } ).explain();
{
“光标”:“基本光标”,
“isMultiKey”:假,
“n”:2548,
“nscannedObjects”:88736,
“nscanned”:88736,
“nscannedObjectsAllPlans”:88736,
“nscannedAllPlans”:88736,
“scanAndOrder”:假,
“indexOnly”:假,
“nYields”:1,
“nChunkSkips”:0,
“毫”:1523,
“索引边界”:{
},
“服务器”:“shuhaimac.local:27017”
}
> db.apps.find({id:/\w{7,16}/i}).count();
2548
> db.apps.find({id:/\w{7,16}/i}).explain();
{
"cursor" : "BtreeCursor id_1 multi",
“isMultiKey”:假,
“n”:2548,
“nscannedObjects”:2548,
“nscanned”:88736,
“nscannedObjectsAllPlans”:2548,
“nscannedAllPlans”:88736,
“scanAndOrder”:假,
“indexOnly”:假,
“nYields”:0,
“nChunkSkips”:0,
“毫”:122,
“索引边界”:{
“ID” : [
[
"",
{
}
],
[
/\w{7,16}/i,
/\w{7,16}/i
]
]
},
“服务器”:“shuhaimac.local:27017”
}
所以,我希望这会有所帮助。:-) 我遇到了同样的问题——我花了一段时间才让 map-reduce 工作。
$response = $Mongo->yourdb->command(array(
"mapreduce" => "yourcollection",
"map" => new MongoCode(" function() { emit( this.groupbykey, this.thestring.length ); } "),
"reduce" => new MongoCode(" function(k, vals) { return Math.max.apply(null, vals); } "),
"query" => array("groupbykey" => "somevalue"),
"out" => array("inline" => 0)
));
响应将保存 map-reduce 结果
Array
(
[results] => Array
(
[0] => Array
(
[_id] => groupbykeyvalue
[value] => 106
)
)
[counts] => Array
(
[input] => 7341
[emit] => 7341
[reduce] => 76
[output] => 1
)
[timeMillis] => 189
[timing] => Array
(
[shardProcessing] => 171
[postProcessing] => 17
)
[shardCounts] => Array
(
[someshard:27017] => Array
祝你好运,如果您需要不同的变体,请告诉我!
与 SQL 不同,MongoDB 并不真正知道字段的长度。最多在索引时它知道该字段是否低于 1024 字节。
因此,您可能必须修复客户端。你可以在$where这里使用 a 但我认为如果你想这样做的话你看错了。
正如@Philipp 所说,您也可以在此处使用和 MR,但您可能再次在这里寻找错误的东西。
MongoDB 中的查询实际上是一个 BSON 文档。因此,查询集的最大长度(取决于您定义为“查询集”的内容)始终为 16MB(目前)。
许多驱动程序提供了一种将结构(散列或字典或其他)编码为 BSON 的方法,允许您判断编码字符串的长度以了解查询的大小。