Mongoid or / any unexpected behavior

I have a problem with mongoid any_of

. I'm trying to find objects that have either one field> 0 or another> 0. My query is:

Model.any_of( => 0, => 0).desc(best_friend_method, method)


It is "translated" into:

  selector: {"$or"=>[{:best_friends_lc_sum=>{"$gt"=>0}, :lc_sum=>{"$gt"=>0}}]},
  options:  {:sort=>[[:best_friends_lc_sum, :desc], [:lc_sum, :desc]]},
  class:    FbAlbum,
  embedded: false>


As I understand it, this is what I want. But this only returns 6 results to me. Model.where( => 0).count

returns me 6 results as well, but Model.where( => 0).count

returns me ~ 850 objects.

I expect my query to return the concatenation of the two: is it a mongoid / mongodb error, or am I doing something wrong?

FYI: mongoid 2.4.5, mongodb 2.0.2, rails 3.1.3

Thank you for your time!


source to share

2 answers

This is because you are only passing one argument, not 2 arguments. So it's as if you have no use $or



Model.any_of({ => 0}, { => 0}).desc(best_friend_method, method)


In this case, the criteria become:

  selector: {"$or"=>[{:best_friends_lc_sum=>{"$gt"=>0}}, {:lc_sum=>{"$gt"=>0}}]},
  options:  {:sort=>[[:best_friends_lc_sum, :desc], [:lc_sum, :desc]]},
  class:    FbAlbum,
  embedded: false>


Sometimes use {}

is required to separate different hashes.



In case it helps anyone ... In Mongoid 3, the Origin gem provides syntax for queries. Here is a list that you can use to write your Mongoid 3 queries . These methods include a method or

that allows you to execute a request $or


# Mongoid query:
  { name: "Martin" }, { name: "Dave" }

# resulting MongoDB query:
  "$or" => [
    { "name" => "Martin" }, { "name" => "Dave" }


Using the OP's original example, it can be rewritten as:

  { => 0 },
  { => 0 }


At least one of the hashes passed to the method or

must match in order to return a record.



All Articles