I’m having an issue with ordering in Mongoid (2.0.0.beta.17 and 2.0.2)/MongoDB. Perhaps I’m just not experienced enough with MongoDB, and some of you can help me understand what I’m doing wrong?
The user-level symptoms are:
- Queries not sorting correctly by date or ID
- User posts are not appearing when they seem like they should be (this is a Twitter-like social networking site for gardeners, and the most recent posts are sometimes not showing up)
irb(main):024:0> Update.all.size
=> 551
Update.ordered.size # (see below for definition)
=> 490
irb(main):010:0> Update.all.select{|u| u.created_at.nil?}
=> []
When I go into the mongo shell, and do:
var cursor = db.updates.find({}, {'_id': 1}).limit(600);
while (cursor.hasNext()) printjson(cursor.next());
I get 454 lines returned.
var cursor = db.updates.find({}, {'_id': 1}).sort({created_at : 1}).limit(600);
while (cursor.hasNext()) printjson(cursor.next());
Also returns 454 lines.
db.updates.find({}).sort({created_at: -1}).limit(1);
returns an update from February 23rd. But I have updates from yesterday in MongoDB.
Any ideas?
My model is:
class Update
include Mongoid::Document
include Mongoid::Timestamps
include Paperclip
field :body
...
index [[ :created_at, Mongo::DESCENDING ]]
...
named_scope :ordered, :order_by => ([[:created_at, :desc]])
...
end
I didn’t figure out WHY, but doing the following seems to fix the problem:
named_scope :ordered, :order_by => ([[:created_at, :desc], [:_id, :desc]])
It seems the secondary ordering helps.
The first of these was being left out of the original query.