Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo: find items that don't have a certain field

People also ask

How do I get only certain fields in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do you check if a field does not exist 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).


Yeah, it's possible using $exists:

db.things.find( { a : { $exists : false } } ); // return if a is missing

When is true, $exists matches the documents that contain the field, including documents where the field value is null. If is false, the query returns only the documents that do not contain the field.


If you don't care if the field is missing or null (or if it's never null) then you can use the slightly shorter and safer:

db.things.find( { a : null } ); // return if a is missing or null

It's safer because $exists will return true even if the field is null, which often is not the desired result and can lead to an NPE.