如何查询mongodb以查找特定字符串/文本字段的长度?另外,您如何找到查询集的最大长度?
答案 0 :(得分:5)
不幸的是aggregation framework不支持“len”运算符在您执行查询时自动将字符串转换为它们的长度。所以你必须在自己的代码中解决这个问题。你可以
这些方法的区别在于,第一个在数据库上运行,而后者在应用程序服务器上运行。我会推荐后一种选择,因为MapReduce使用起来非常慢且很麻烦。
答案 1 :(得分:4)
天空是极限!不,实际上16 MB
中的文档为mongodb
。这可以是记录中字符串的最大长度。
为了在查询集中找到最大长度,您可以执行以下操作:
答案 2 :(得分:2)
如何使用正则表达式。
> 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(); { "cursor" : "BasicCursor", "isMultiKey" : false, "n" : 2548, "nscannedObjects" : 88736, "nscanned" : 88736, "nscannedObjectsAllPlans" : 88736, "nscannedAllPlans" : 88736, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 1, "nChunkSkips" : 0, "millis" : 1523, "indexBounds" : { }, "server" : "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" : false, "n" : 2548, "nscannedObjects" : 2548, "nscanned" : 88736, "nscannedObjectsAllPlans" : 2548, "nscannedAllPlans" : 88736, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 0, "nChunkSkips" : 0, "millis" : 122, "indexBounds" : { "id" : [ [ "", { } ], [ /\w{7,16}/i, /\w{7,16}/i ] ] }, "server" : "shuhaimac.local:27017" }
答案 3 :(得分:1)
所以,我希望这会有所帮助。 :-)我遇到了同样的问题 - 我花了一些时间让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
祝你好运,如果你需要一个不同的变种,请告诉我!
答案 4 :(得分:0)
从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 }
答案 5 :(得分:-1)
与SQL不同,MongoDB并不真正知道字段的长度。最多在索引时它知道该字段是否在1024字节以下。
因此,您可能需要修复客户端。你可以在这里使用$where
,但如果你想这样做,我认为你看错了。
你也可以在这里使用和MR作为@Philipp声明,但你又可能在这里看错了。
MongoDB中的查询实际上是BSON文档。因此,查询集的最大长度(取决于您定义为“查询集”的内容)始终为16MB(此刻)。
许多驱动程序提供了一种方法,通过这种方法将结构(散列或字典或其他)编码到BSON,允许您判断编码字符串的长度,以了解查询的大小。