开发者

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 Things 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜