I have rails app with mongoid model. There’s counter field in this model which is integer. I want to sort entries by this field casted to boolean, like
MyModel.desc("counter::boolean") # casting in postgres-like syntax
so entries with counter > 0 go first and those with counter == 0 go last.
I also use created_at sorting on this expression which works correctly only for same value of counter, that’s why i need to have only two possible values. Not necessarily true/false, it could be 1/0.
Mongodb doesn’t support custom sorting functions (there’s open ticket for it).
Is such casting it possible to do in mongoid/mongodb? If no, maybe any workarounds?
Not very pretty way, but you might create additional field in documents with value depending exactly on your sorting scheme, like: “order”: cast a value to boolean and then sort by it.
Suprisingly – it’s a quite common way to get around mongodb’s limitations.