2013-02-01 51 views

回答

4

天空是極限!不,實際上它是16 MB作爲mongodb中的文檔。這可以是記錄中字符串的最大長度。

爲了找到查詢集的最大長度,你可以四處做這項工作:

  1. 與文本本身保持文本的長度在一起。
  2. 按照長度降序對結果集進行排序。
  3. 獲取具有最大長度的第一個元素。
5

不幸的是,aggregation framework不支持在執行查詢時自動將字符串轉換爲其長度的「len」運算符。所以你必須在你自己的代碼中解決這個問題。你可以

  1. 使用MapReduce的函數來計算字符串長度
  2. 查詢字符串,並計算應用層上它們的長度

這些方法之間的區別是數據庫上的第一次運行而後者在你的應用服務器上運行。我會推薦後一種選擇,因爲MapReduce的使用速度可能非常慢並且很麻煩。

-1

與SQL不同,MongoDB並不真正知道字段的長度。它至多在索引時知道該字段不在1024字節之內。

因此,您可能必須修復客戶端。你可以在這裏使用$where,但如果你想這樣做,我認爲你看着這個錯誤。

你也可以在@Philipp使用和MR在這裏,但是你也可能會在這裏看到錯誤的東西。

MongoDB中的查詢實際上是一個BSON文檔。因此,查詢集的最大長度(取決於您定義的「查詢集」)總是16MB(目前)。

許多驅動程序提供了一種方法來將結構(散列或字典或其他)編碼爲BSON,從而允許您判斷編碼字符串的長度以瞭解查詢的大小。

+5

這簡直是不真實的:MongoDB絕對知道字符串的長度,它是類型字符串的bson規範的一部分,前4個字節是字符串的長度。沒有運營商允許您查詢。 –

+0

@AsyaKamsky在寫這篇文章之前,應該先檢查一下規範 – Sammaye

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" 
} 
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 

祝你好運,讓我知道如果你需要一個不同的變種!