Example 1: Query for “not null” in Specific Field
Consider a MongoDB collection named “students” containing documents representing student profiles. Each document includes a field named “name” that stores the student’s name. To retrieve documents where the “name” field is not null, we can use the $ne operator as follows
db.students.find({ name: { $ne: null } });
Output:
[
{
"_id": 1,
"name": "Alice",
"age": 20,
"grade": "A"
},
{
"_id": 2,
"name": "Bob",
"age": null,
"grade": "B"
},
{
"_id": 3,
"name": "Charlie",
"age": 22,
"grade": null
},
{
"_id": 4,
"name": "David",
"age": 23,
"grade": "C"
},
{
"_id": 5,
"name": "Eve",
"age": null,
"grade": null
}
]
Explanation: This query will return all documents from the “students” collection where the “name” field exists and is not null.
How to Query For Is Not Null in MongoDB in a Specific Field?
MongoDB with its flexible document–oriented structure, offers powerful querying capabilities to extract meaningful insights from your data. One common requirement in database querying is to retrieve documents where a specific field is not null.
In this article, We will learn about How to Query For Is Not Null in MongoDB in a Specific Field by understanding various examples with the output in detail.
Contact Us