2016-08-22 64 views
1

我的收藏:如何計算基於獨特的嵌入式陣列值

{ "_id" : 1, "type" : "A", "types" : [ "type1://asfasd", "type2://xcvxcv" ] } 
{ "_id" : 2, "type" : "B", "types" : [ "type1://xcv" ] } 
{ "_id" : 3, "type" : "C", "types" : [ "type2://aewqqwe" ] } 
{ "_id" : 4, "type" : "D", "types" : [ "type2://xcxc" ] } 

我想最終的結果來算,告訴我:

type1 -> 2 (because there are total of 2 documents that has type1) 
type2 -> 3 (because there are total of 3 documents that has type2) 
+0

請問您所有的文件'types'值前綴( 'type1','type2')的長度是恆定的(這裏是5)?或者有不同長度的前綴(如'http'和'https')? – tarashypka

+0

不是沒有固定的大小(可以是type1://,othertype3://)。我想在://之前至少有3個字母是可以的(如果substr是在這裏計劃的)? – shayy

回答

0

有了地圖,減少您可以使用正則表達式來提取根據你想要的字符串即TYPE1,TYPE2,type69等

至於I K文件現在,您不能在彙總管道和組階段中使用正則表達式。

因此,在映射階段,迭代類型陣列,使用正則表達式來提取你的字符串,即類型1,類型2,比發射這個字符串作爲密鑰與1
的值在降低階段,所有的值使用相同的密鑰將是一個列表,比你只算表的長度:您的數據

var map = function map(){ 
    for (type in this.types){ 
     var str = this.types[type]; 
     var rx = /type\d+/; 
     var match = str.match(rx); 
     emit (match[0], 1); 
    } 
}; 

var reduce = function(key, values){ 
    return values.length 
}; 


db.runCommand({"mapReduce":"collection", map:map, reduce:reduce, out:{replace:"collection2"}}) 

防爆輸出:

{ "_id" : "type1", "value" : 2 } 
{ "_id" : "type2", "value" : 3 }