Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Check that Field Exists with MongoDB?
In MongoDB, you can check if a field exists in documents using the $exists operator. To ensure the field is not null, combine it with the $ne operator.
Syntax
db.collection.find({ "fieldName": { $exists: true, $ne: null } })
Sample Data
db.checkFieldExistDemo.insertMany([
{
"EmployeeId": 1,
"EmployeeName": "John",
"isMarried": true,
"EmployeeSalary": 4648585
},
{
"StudentId": 2,
"StudentName": "John",
"isMarried": false,
"StudentAge": 19
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c76f7b31e9c5dd6f1f78281"),
ObjectId("5c76f7e11e9c5dd6f1f78282")
]
}
Display all documents from the collection ?
db.checkFieldExistDemo.find().pretty();
{
"_id": ObjectId("5c76f7b31e9c5dd6f1f78281"),
"EmployeeId": 1,
"EmployeeName": "John",
"isMarried": true,
"EmployeeSalary": 4648585
}
{
"_id": ObjectId("5c76f7e11e9c5dd6f1f78282"),
"StudentId": 2,
"StudentName": "John",
"isMarried": false,
"StudentAge": 19
}
Case 1: Field Present in Multiple Documents
Check for the "isMarried" field that exists in both documents ?
db.checkFieldExistDemo.find({ "isMarried": { $exists: true, $ne: null } }).pretty();
{
"_id": ObjectId("5c76f7b31e9c5dd6f1f78281"),
"EmployeeId": 1,
"EmployeeName": "John",
"isMarried": true,
"EmployeeSalary": 4648585
}
{
"_id": ObjectId("5c76f7e11e9c5dd6f1f78282"),
"StudentId": 2,
"StudentName": "John",
"isMarried": false,
"StudentAge": 19
}
Case 2: Field Present in Single Document
Check for the "StudentName" field that exists only in one document ?
db.checkFieldExistDemo.find({ "StudentName": { $exists: true, $ne: null } }).pretty();
{
"_id": ObjectId("5c76f7e11e9c5dd6f1f78282"),
"StudentId": 2,
"StudentName": "John",
"isMarried": false,
"StudentAge": 19
}
Key Points
-
$exists: truematches documents where the field is present -
$ne: nullexcludes documents where the field is null - Combining both ensures the field exists and has a value
Conclusion
Use $exists: true with $ne: null to check if a field exists and contains a value. This combination filters out both missing fields and null values effectively.
Advertisements
