2011-01-24 53 views
0

我試圖用Mongoid執行一個或多或少的高級查詢,它基本上獲取日期範圍的度量標準,將它們按天分組,然後總結每天的值,它也應該告訴我每個項目有多少條目天。使用Mongoid分組結果並彙總一個查詢中的字段?

我非常懷疑這可以用Mongoid的活動記錄部分來完成,但我不知道如何直接在mongo驅動程序上執行查詢。

我的模型:

class Metric 
    include Mongoid::Document 

    field :id_session, :type => Integer 
    field :metric,  :type => Integer 
    field :value,   :type => Integer 
    field :date,   :type => Date 
    field :time,   :type => Time 

    validates_numericality_of :value 
    validates_presence_of :id_session, :metric, :value 

    before_create :set_date 

    def set_date 
    self.time = Time.now 
    self.date = Date.now 
    end 

end 

我已經能夠簡單地通過使用Metric.distinct度日日期分組的結果(:日期),但我不知道如何做一個總和計數這些結果因爲我無法在結果中使用該方法。

任何想法?我更喜歡留在Mongoid活動記錄方法中,但是如果有人知道我可以直接在MongoDB驅動上執行查詢,那也會有幫助。

謝謝!

回答

0

設法得到它的工作

result = Metric.collection.group(
    ['date'] , nil, {:count => 0, :value => 0}, "function(x, y) { y.count++; y.value += x.value }" 
) 

現金去答案的this page

相關問題