我需要一些帮助,通过'ruby中的查询来排序mongo'组。
我让小组按部分工作。下面的查询按小时对记录进行分组,返回的结果如下:
{"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)
答案 0 :(得分:0)
Ruby有一个内置的sort_by函数用于enumberables(包括数组)。
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}
#]
编辑:您还可以将时间解析为块中的Time对象,以确保正确排序。
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}
# ]