Fork me on GitHub

Back Home

Sorting an EmbeddedDocument with MongoMapper

by Phil

I had this issue recently when trying to sort items in an EmbeddedDocument. Say you have a "Post" Document and a "Comment" EmbeddedDocument. If you want to sort the comments by the created_at field (which is pretty likely), it isn't as easy as you would think, using MongoMapper (at the moment anyway).

However, there is a nice clean alternative that can be used to achieve the same results. Simply use the "sort_by" method like so, passing in a symbol of the field to sort as a proc:-

...and for descending order:-

Here is the original google group thread.


blog comments powered by Disqus
© 2009 Phil McClure This site was developed using Compass, Blueprint and Ruby on Rails - Much thanks to these guys!