Order items in MongoDB according to the size of an array with MongoMapper?
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 Thing
s ordered from those with the most tags to those with the least. The tags in this example are simply strings within the tags arr开发者_C百科ay. 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.
class Thing
include MongoMapper::Document
key :name, String
key :tags, Array
key :tag_size, Integer, :default => 0, :index => true
end
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
精彩评论