1

I'm using Mongoid to build a Rails 4 app.

The problem I'm having right now is how to filter some Mongoid objects through their own relations and have a Mongoid::Criteria at the end instead of an Array.

This is some example code:

class Editor
  include Mongoid::Document

  has_many :books

  def likes
    books.collect { |book| book.likes }
  end
end

class Book
  include Mongoid::Document

  belongs_to :editor
end

What I would like to be able to do is something like:

Editor.last.likes.where(:created_at.gt => 10.days.ago)

but of course this doesn't work as Editor.last.likes returns an Array, not a Mongoid::Criteria

I know Mongoid has an aggregation framework but it's not entirely clear to me how to use it, nor if it's the best way to solve my problem.

Suggestions?

TIA, ngw

Community
  • 1
  • 1
ngw
  • 1,222
  • 1
  • 14
  • 34

1 Answers1

1

The biggest problem you have here is that MongoDB does not do joins like a relational database does. All of the work you are getting for convenience when traversing object properties is being done client side while pulling in the 'related' documents over the wire in a query. But in sending a query, the two collections cannot be joined.

Your workaround solution is to work with the data you can get at in separate queries in order to target the results. One approach is here: rails mongoid criteria find by association

There should be other examples on Stack Overflow. You're not the first to ask.

Community
  • 1
  • 1
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317