How to check if field exists in MongoDb?

In MongoDB, we can check whether the field exists or not in two different ways:

  • By using the $exists operator and
  • By setting the value of that field to null

Ignore field using $exists operator

Let’s say we have a collection called users and we want to query documents where the age field is exist or not. The query would look like this:

    age: { $exists: false } 

This query returns all the user’s documents where the age field is missing.

Ignore field setting field value to null

We can also verify whether the particular field exists in the MongoDB document or not by using the following query:

    age: null 

What the above query does is:

The { age : null } query matches documents that either contain the age field whose value is null or that do not contain the age field.

Either way, we can check whether the field in the MongoDB document exists or not.


Leave a Reply

Notify of
Inline Feedbacks
View all comments