Open In App

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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

  • Check the existence of the field in the student collection:
db.student.find({name:{$exists:true}})

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

  • Check the existence of the field of the embedded document:
db.student.find({"details.game":{$exists:true}})

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


Last Updated : 22 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads