nc.
nc.

Reputation: 7259

Mongoid: Criteria #find - How do I limit find to the results in the criteria?

I am having some trouble understanding something with criteria and #find.

I have a bit of code that looks:

def returns_criteria
  MyModel.in(...)
end

My understanding of criteria was that the results get more restrictive as you chain things. That seems to be how relation collections work, at least, which may be misleading me.

So my expectation was that if I called:

returns_criteria.find(some_id)

then it would look for an object with id some_id within the results found by the MyModel.in call. But this is not happening, it seems like #find is called like it would be called on MyModel.

I would like to restrict this #find to the results of the currently specified criteria. Can I do this somehow?

Minimal Repro Repo: https://github.com/nchelluri/mongoid-in-find

Output of running in.rb: https://gist.github.com/nchelluri/6401850

Upvotes: 0

Views: 285

Answers (1)

Zach Kemp
Zach Kemp

Reputation: 11904

I think I've found what's going on here. If you direct Moped to log to $stdout you can take a closer look at what commands it's sending to the database:

Moped.logger = Logger.new($stdout)
Moped.logger.level = Logger::DEBUG

The selector hash for the original in criteria object is:

selector={"_id"=>{"$in"=>["5222b8edf273e6eeb1000001", "5222b8edf273e6eeb1000002"]}

But if you chain 'find' onto it, it becomes:

selector={"_id"=>"5222b8edf273e6eeb1000003"}

...which is basically a result of the standard behavior of a Ruby hash. You've reassigned the "_id" key from the original in selector with the one from find. This may simply be a limitation of Mongoid/Moped, and I'm not sure how you would work around it. At the same time, I'm struggling to find a case where you would need to search on multiple id criteria, but I'll grant you that as a test case, it's a bit counterintuitive.

Upvotes: 1

Related Questions