简体   繁体   中英

Displaying MongoDB results in chartkick using ruby on rails

I have this output from a query in MongoDB using Ruby :

irb(main):087:0>   data = col.find({}, :fields => ["result", "time"])
=> <Mongo::Cursor:0x14768b8 namespace='spark.light' @selector={} @cursor_id=>

irb(main):090:0> data.first
=> {"_id"=>BSON::ObjectId('537d961197c20960ad000001'), "result"=>2177, "time"=>2014-05-22 06:15:45 UTC}

Now I want to give this data to chartkick running on Ruby on Rails to draw a linechart .The input shall looks like this :

"2014-05-22 06:15:45 UTC" => "2177"

Is there any clean way to do that ?

This would transform records into a hash of time => result :

Hash[data.map do |item|
  [item['time'], item['result']]
end]

# => { 2014-05-22 06:15:45 UTC => 2177, 2014-05-22 06:20:00 UTC => 1000 }

Hash#values_atHash::[]方法一起使用:

Hash[data.first.values_at('time', 'result')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM