Mongoid Tip: Merge & Sort MongoDB Queries

Become a Subscriber

Working with the Mongoid adapter can sometimes be a bit frustrating as both the library and ActiveModel are treated as second-class citizens in the Rails world. If you have ever wondered how to make separate mongodb queries and merge them in Rails, then this little guide is perfect for you.

Keep It Simple Stupid

As with most things in Ruby, if it feels complex, then you are probably doing it wrong; or at the very least could be doing it better. Merging Mongoid queries is a perfect case for the KISS principle. I have seen other solutions ranging from complex aggregations (aggregation is like a mini query language that exists on the MongoDB driver) to franken-models that kluge together other models. Here’s a better way using simple array concatenation:

stream = Post.all | Tweet.all

Oh and if you want to start doing some fancier things, just use any array method of your choosing:

stream.sort_by { |i| i.published_date }

Were you expecting something more complex? Sorry to disappoint!