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執行聚合?