Open In App
Related Articles

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

Improve Article
Improve
Save Article
Save
Like Article
Like

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.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 22 Nov, 2021
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials