Really not much more to tell than what is already in the question.
using mongoid:
People.asc(:age)
I get nil value first.
is there a way to always return nil last, or to tell mongodb to treat nil as very high?
Exactly like what is answered for the same problem in sql here
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:
So you’re not alone in wanting to put
nulls at one end or the other.I think the best you can do right now is to do it in Ruby, something like this:
I don’t use Mongoid but presumably
ascgives you an Enumerable, if not then perhaps you could stick ato_ain there. Of course this sort of hackery is useless if you’re paginating.