I'm pretty sure the answer is "no" for MongoDB. There's no way to supply a custom sorting function, you can only supply the keys to sort on. There is a request for custom sorting functions and they even mention your particular use case:
javascript sort helper for custom sorting / indexing
[...]
Could this be used to sort alphabetically on a field, and put documents with a null value at the end of the result set?
[...]
@nick - yes
So you're not alone in wanting to put null
s at one end or the other.
I think the best you can do right now is to do it in Ruby, something like this:
nils, not_nils = People.asc(:age).partition { |p| p.age.nil? }
people = not_nils + nils
I don't use Mongoid but presumably asc
gives you an Enumerable, if not then perhaps you could stick a to_a
in there. Of course this sort of hackery is useless if you're paginating.