开发者

Ruby MongoDB- how to sort records based on datetime?

开发者 https://www.devze.com 2023-01-15 15:21 出处:网络
I must have done it in a wrong way: the records printed out are out of order, even though they are inserted into db one at a time. Here is the code:

I must have done it in a wrong way: the records printed out are out of order, even though they are inserted into db one at a time. Here is the code:

get '/' do
  db = Mongo::Connection.new("localhost", 27017).db("testdb")
  @notes = db.collection('notes')
  @notelist = Set.new()
  @notes.find().each{|record| @notelist.add(record)}
  erb :list
end

post '/addnote' do
  db = Mongo::Connection.new("localhost", 27017).db("testdb")
  col1 = db.collection('notes')
  col1.insert(
 开发者_如何学编程 {
    "guestname" => "#{params[:post][:guestname]}",
    "note"      => "#{params[:post][:note]}",
    "datetime"  => Time.now.strftime("%I:%M %p %d-%b-%Y")
  })
redirect '/'
end

And here is the erb template:

<p><%= @notelist.size() %> notes entered by guests:</p>
<ul>
  <% @notelist.each do |record| %>
    <li><font color='blue'><%= record['guestname'].to_s() + 
    "</font> at <i>" + record['datetime'].to_s() +"</i> wrote: " + 
    record['note'].to_s() %></li>
  <% end %>
</ul>

I am trying to get all records out of the db in an order of datetime, how can I achieve that?

Thanks a lot in advance.

Updated info:

On second thought, I change the data type from time to unix epoch, so sorting them would be better and easier.


A few notes here:

You can get records in order by adding a sort:

@notes.find({}, :sort => 'datetime')

You do not need to iterate before entering your template. The 'find' method returns a cursor, which itself is iterable. So

@notelist = Set.new()
@notes.find().each{|record| @notelist.add(record)}

Should read

@notelist = @notes.find({}, :sort => 'datetime')

It's very inefficient to establish a new connection on each request. You should establish the connection on a configure block, and cache the database there:

configure do
  DB = Mongo::Connection.new.db("testdb")
end

Then just use the reference to DB in your requests.

0

精彩评论

暂无评论...
验证码 换一张
取 消