I’d like to select a collection of items ordered based on the number of items within an array. Hopefully the following example will clarify my rather poor explanation:
class Thing
include MongoMapper::Document
key :name, String
key :tags, Array
end
I’d like to retrieve all Things ordered from those with the most tags to those with the least. The tags in this example are simply strings within the tags array. Basically I want something which means the same as this (but works):
Thing.all(:order => 'tags.count desc')
Is this possible?
The core server currently doesn’t support computing the size of an array and then sorting by that. I think that your best bet for the moment would be to cache the array size on your own, and add an index on that field.
Then just add a callback to your model that updates tag_size on save.
If this is a feature you’d like to see in the core server, you can add a case here:
http://jira.mongodb.org/browse/SERVER