Created
January 31, 2019 16:32
-
-
Save deevis/95ec92b2342e28e009891b22c41ae7d8 to your computer and use it in GitHub Desktop.
MongoDB group aggregation with count and sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
q = [ | |
{ "$match" => { "created_at" => { "$gte" => 60.days.ago, "$lte" => 0.days.ago }}}, | |
{ "$group" => { _id: { | |
'year' => {'$year' => "$created_at"}, | |
'month' => {'$month' => "$created_at"}, | |
'day' => {'$dayOfMonth' => "$created_at"}, | |
"errorable_type" => "$errorable_type", | |
"error_class" => "$error_class" | |
}, | |
count: { "$sum" => 1 } | |
} | |
}, | |
{ "$sort" => { "_id.year" => -1, "_id.month" => -1, "_id.day" => -1, "count" => -1} } | |
] | |
result = TaskError.collection.aggregate( q ) | |
start = Time.now; last_date=nil;result.each{|r| date = "#{r.dig('_id','year')}-#{r.dig('_id','month')}-#{r.dig('_id','day')}"; if date != last_date; puts "\n\n#{date}\n\n"; last_date = date; end; puts " #{r['count']} => #{r['_id']}"};puts Time.now - start | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment