How to Check Field Existence in MongoDB
Let’s consider a collection named students
in the school
database. This collection contains documents with information about students, but not all documents have the same fields. Here are some sample documents.
[
{ "_id": 1, "name": "Alice", "age": 18, "grade": "A" },
{ "_id": 2, "name": "Bob", "age": 20 },
{ "_id": 3, "name": "Charlie", "grade": "B" },
{ "_id": 4, "name": "David", "age": 22, "grade": "C" }
]
Example 1: Exists and Not Equal To
To find documents where the age
field exists and is not equal to 18, we will use the following query.
db.students.find({ age: { $exists: true, $ne: 18 } })
Output:
[
{ "_id": 2, "name": "Bob", "age": 20 },
{ "_id": 4, "name": "David", "age": 22 }
]
Explanation: The query retrieves documents where the age
field exists and is not equal to 18. Bob and David have ages that exist and are not 18.
Example 2: Handling Null Values
To find documents where the grade
field exists and is not null, we use the following query.
db.students.find({ grade: { $exists: true, $ne: null } })
Output:
[
{ "_id": 1, "name": "Alice", "age": 18, "grade": "A" },
{ "_id": 3, "name": "Charlie", "grade": "B" },
{ "_id": 4, "name": "David", "age": 22, "grade": "C" }
]
Explanation: The query retrieves documents where the grade
field exists and is not null. Alice, Charlie, and David have non-null grades.
How to Check Field Existence in MongoDB?
MongoDB is a NoSQL database that offers a variety of operators to enhance the flexibility and precision of queries. One such operator is $exists
, which is used to check the presence of a field in a document.
In this article will learn about the $exists
Operator in MongoDB by covering its syntax and practical applications. We will also learn about how to query data using Atlas Search.