Open In App

MongoDB – Check the existence of the fields in the specified collection

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). When the value of $exists operator is set to false, then this operator returns only those documents that don’t contain the specified field. 

Syntax:



{ field: { $exists: <boolean> } }

Examples: 



In the following example, we are working with:

Database: gfg

Collections: student

Document: Three documents contains name and age of the students

db.student.find({name:{$exists:true}})

Here, we check the field exists or not in the student collection using $exists operator.

db.student.find({"details.game":{$exists:true}})

Here, we check the field of the embedded document is exists or not using the $exists operator.

Article Tags :