views:

249

answers:

1

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?

+2  A: 

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

Kyle Banker
Ah, fair enough - I assumed it was supported. Thanks for the alternative suggestion though, that does sound like my best bet.
Splash