问题
I'm having a difficult time doing something such as:
Something.where(:field => nil)
or
Something.where(:field => { '$eq' => nil })
What's the right way to handle this in Mongoid?
回答1:
That's the right way to do it. To find cars whose engine is nil
, for example, use:
# Cars that have a _nil_ engine.
Car.where(:engine => nil)
If you're trying to look for the absence of a field (rather than one that's set to nil
), use the $exists
predicate:
# Cars that lack an engine entirely.
Car.where(:engine.exists => false)
Note that setting a field foo
to be nil
and lacking a field named foo
are two different things.
来源:https://stackoverflow.com/questions/8963054/mongoid-how-to-query-for-all-objects-where-value-is-nil