Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select MongoDB documents where a field either does not exist, is null, or is false?

Suppose I have a collection that contains the following documents:

{ "_id": 1, name: "Apple" } { "_id": 2, name: "Banana", "is_reported": null } { "_id": 3, name: "Cherry", "is_reported": false } { "_id": 4, name: "Kiwi",   "is_reported": true } 

Is there a simpler query to select all documents where "is_reported" is in a falsy state; that is, either non-existent, null, or false? That is, a query that selects Apple, Banana, and Cherry, but not Kiwi?

According to the MongoDB FAQ, { "is_reported": null } will select documents where "is_reported" is either null or nonexistent, but it still doesn't select documents where "is_reported" is false.

Right now I have the following query, which works fine, but it just doesn't seem very elegant. If there are multiple fields that I need to select on, it gets messy very fast. Is there a better query that achieves the same end result?

db.fruits.find({ $or: [ { "is_reported": null }, { "is_reported": false } ] }) 
like image 529
sffc Avatar asked Mar 10 '14 01:03

sffc


People also ask

How do you check field is exist or not 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).

IS NOT NULL condition in MongoDB?

To query for is not null value, we can use the $ne operator as well as the $eq operator and specify the desired value that we want to query for. This guide aims to provide readers with different ways and examples for the same to query for is not null values in MongoDB.

How do I query 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 } ).


1 Answers

You can do this with $in:

db.fruits.find({is_reported: {$in: [null, false]}}) 

returns:

{   "_id": 1,   "name": "Apple" } {   "_id": 2,   "name": "Banana",   "is_reported": null } {   "_id": 3,   "name": "Cherry",   "is_reported": false } 

You could also flip things around logically and use $ne if you don't have any values besides true to exclude:

db.fruits.find({is_reported: {$ne: true}}) 
like image 143
JohnnyHK Avatar answered Oct 08 '22 11:10

JohnnyHK