1

我需要一些帮助在 ruby​​ 中对 mongo 'group by' 查询进行排序。

我让小组按部分工作。下面的查询按小时对记录进行分组,返回如下结果:

{"date"=>"2013,4,2,18,0,0,0", "count"=>1.0}
{"date"=>"2013,4,9,19,0,0,0", "count"=>1.0}
{"date"=>"2013,3,13,2,0,0,0", "count"=>3.0}

理想情况下,结果将按“日期”字段排序。

data = db[collection_name].group(
"function(doc) {
var dateKey = doc.created_at.getFullYear() + ',' +
(doc.created_at.getMonth() + 1) + ',' + doc.created_at.getDate() + ',' +
doc.created_at.getHours() + ',0,0,0';
return {'date': dateKey};}", 
{"parent_id" => parent_id, "checked" => true},
{ :count => 0 },
"function(doc, y){y.count++}",
true)
4

1 回答 1

0

Ruby 有一个用于可数(包括数组)的内置sort_by函数。

array = [
  {"date"=>"2013,4,2,18,0,0,0", "count"=>1.0},
  {"date"=>"2013,4,9,19,0,0,0", "count"=>1.0},
  {"date"=>"2013,3,13,2,0,0,0", "count"=>3.0}
]

p array.sort_by { |item| item['date'] }

# => [
#  {"date"=>"2013,3,13,2,0,0,0", "count"=>3.0}, 
#  {"date"=>"2013,4,2,18,0,0,0", "count"=>1.0}, 
#  {"date"=>"2013,4,9,19,0,0,0", "count"=>1.0}
#]

编辑:您还可以将时间解析为块中的时间对象以确保正确排序。

require 'time'

array = [
  {"date"=>"2013,4,2,18,0,0,0", "count"=>1.0},
  {"date"=>"2013,4,9,19,0,0,0", "count"=>1.0},
  {"date"=>"2013,3,13,2,0,0,0", "count"=>3.0},
  {"date"=>"2013,4,13,2,0,0,0", "count"=>2.0}
]

p array.sort_by { |item| Time.parse(item['date']) }

# => [
#   {"date"=>"2013,3,13,2,0,0,0", "count"=>3.0}, 
#   {"date"=>"2013,4,2,18,0,0,0", "count"=>1.0}, 
#   {"date"=>"2013,4,9,19,0,0,0", "count"=>1.0}, 
#   {"date"=>"2013,4,13,2,0,0,0", "count"=>2.0}
# ]
于 2013-04-15T06:36:21.123 回答