你如何查询 MongoDB 来查找特定字符串/文本字段的长度?
而且,你如何找到查询集的最大长度?
你如何查询 MongoDB 来查找特定字符串/文本字段的长度?
而且,你如何找到查询集的最大长度?
天空是极限!不,实际上在mongodb
中,一个文档的大小限制为16 MB
。这也是记录中字符串的最大长度。
为了在查询集中找到最大长度,您可以使用以下方法:
从 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({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" }
希望这能帮到你。:-) 我也遇到了同样的问题,花了一段时间才让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)
));
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
,但如果您想这样做,我认为您的思路有误。
正如@Philipp所述,您也可以在这里使用MR,但同样,您可能正在研究错误的内容。
MongoDB中的查询实际上是一个BSON文档。因此,查询集的最大长度(取决于您定义的“查询集”)始终为16MB(目前为止)。
许多驱动程序提供了一种编码结构(哈希或字典或其他)到BSON的方法,使您可以判断编码字符串的长度以了解查询的大小。