Question

I'm using MongoDB through Mongoid with Rails 3 and observe this strange behavior when doing query in rails console:

> Table.where(:field => {"$exists" => true}).count
=> 3735
> Table.where(:field => {"$exists" => true}, :field => {"$ne" => ""}).count
=> 14878 # wtf???
> Table.where(:field => {"$exists" => true}, :field => "").count
=> 0 # at least it's not negative
> Table.where(:field => {"$exists" => false}).count
=> 11143

Since 11143 + 3735 = 14878, I assume that where(:field => {"$exists" => true}, :field => {"$ne" => ""}) also counts those records in which :field is not present (because nil != ""?). However, I believed conditions listed in #where would be joined with and, so it should match only those records where :field is not empty string AND is present.

Was it helpful?

Solution

You say "However, I believed conditions listed in #where would be joined with 'and'," but this is not correct. The conditions are a hash, and you have a collision on the key :field. Ruby silently uses the last value.

Please review the documentation for selection in Mongoid http://mongoid.org/en/origin/docs/selection.html, and use #and for a proper 'and' conjunction. Note that you can #inspect your query and examine the returned Criteria object. For example:

puts Table.where(:field => {"$exists" => true}, :field => {"$ne" => ""}).inspect

Hope that this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top