2011-05-26 47 views
2

我正在使用Rail 3與Mongoid作爲我的ODM。如何更有效地聚合這些數據?

我已導入了下列文件到的MongoDB:

{ "make" : "Make A", "model": "Model 1", "variant" : "Variant 1" } 
{ "make" : "Make B", "model": "Model 3", "variant" : "Variant 1" } 
{ "make" : "Make A", "model": "Model 2", "variant" : "Variant 2" } 
{ "make" : "Make A", "model": "Model 2", "variant" : "Variant 1" } 

下面的代碼產生已排序的不同值的嵌套散列:

@makes = Item.all.distinct(:make).sort 

@models = {} 
@makes.each do |make| 
    @models[make] = Item.where(:make => make).distinct(:model).sort 
end 

@output = {} 
@models.each_pair do |make, models| 
    @output[make] = {} 
    models.each do |model| 
    @output[make][model] = Item.where(:make => make, :model => model).distinct(:variant).sort 
    end 
end 

所得散列看起來像這樣:

{ 
    "Make A" => { 
    "Model 1" => ["Variant 1"], 
    "Model 2" => ["Variant 1", "Variant 2"] 
    }, 
    "Make B" => { 
     "Model 3" => ["Variant 1"] 
    } 
} 

這一切工作正常,但效率非常低,因爲它涉及太多的查詢秒。有沒有更好的方式實現這一點,也許通過讓MongoDB執行聚合?

回答

0

我解決了這個使用MongoDB的具有以下PARAMATERS的MapReduce功能:

map = function() { 
    emit(1, { make: this.make, model: this.model, variant: this.variant }); 
} 

reduce = function(key, values) { 
    var result = {}; 
    values.forEach(function(value) { 
    if (!result[value.make]) result[value.make] = {}; 
    if (!result[value.make][value.model]) result[value.make][value.model] = []; 
    result[value.make][value.model].push(value.variant); 
    }); 
    return result; 
} 

這將返回一個MongoDB的結果相同的格式,上面的Ruby的哈希值。