Mongoid: how to query for all objects where value is nil?

回眸只為那壹抹淺笑 提交于 2019-12-08 15:13:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!