Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 663
randombits Avatar asked Jan 22 '12 17:01

randombits


People also ask

How do I display null values in MongoDB?

MongoDB fetch documents containing 'null' If we want to fetch documents from the collection "testtable" which contains the value of "interest" is null, the following mongodb command can be used : >db. testtable. find( { "interest" : null } ).

How do I check if a field is empty in MongoDB?

In MongoDB, we can check the existence of the field in the specified collection using the $exists operator. When the value of $exists operator is set to true, then this operator matches the document that contains the specified field(including the documents where the value of that field is null).

How do I find a missing field in MongoDB?

Use BsonNull. Value with the MongoDB C# driver to query for null or missing fields in MongoDB.

Does MongoDB store null value?

Indeed, it's not possible to store null values in a MongoDB document using a DataFrame. The Python None values are considered as missing attributes accordingly to this NoSQL specific allowance. However, if your column is numerical, you can force writing a null value by setting it to NaN.


1 Answers

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.

like image 133
John Feminella Avatar answered Oct 03 '22 06:10

John Feminella