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(best_friend_method.gt => 0, method.gt => 0).desc(best_friend_method, method)

      

It is "translated" into:

#<Mongoid::Criteria
  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(:best_friends_lc_sum.gt => 0).count

returns me 6 results as well, but Model.where(:lc_sum.gt => 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!

+3


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

.

Try:

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

      



In this case, the criteria become:

#<Mongoid::Criteria
  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.

+9


source


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:
Model.or(
  { name: "Martin" }, { name: "Dave" }
)

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

      

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



Model.or(
  { best_friend_method.gt => 0 },
  { method.gt => 0 }
).order_by(
  best_friend_method,
  method
)

      

At least one of the hashes passed to the method or

must match in order to return a record.

0


source







All Articles