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
Find items that do not have a certain field in MongoDB?
To find documents that do not have a certain field in MongoDB, use the $exists operator with the value false. This operator checks whether a field is present in the document, regardless of its value.
Syntax
db.collection.find({"fieldName": {$exists: false}})
Sample Data
Let's create a collection with documents where some have a specific field and others don't ?
db.findDocumentDoNotHaveCertainFields.insertMany([
{"UserId": 101, "UserName": "John", "UserAge": 21},
{"UserName": "David", "UserAge": 22, "UserFavouriteSubject": ["C", "Java"]},
{"UserName": "Bob", "UserAge": 24, "UserFavouriteSubject": ["MongoDB", "MySQL"]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c8a95fb6cea1f28b7aa07fb"),
ObjectId("5c8a96116cea1f28b7aa07fc"),
ObjectId("5c8a96306cea1f28b7aa07fd")
]
}
View All Documents
db.findDocumentDoNotHaveCertainFields.find().pretty()
{
"_id": ObjectId("5c8a95fb6cea1f28b7aa07fb"),
"UserId": 101,
"UserName": "John",
"UserAge": 21
}
{
"_id": ObjectId("5c8a96116cea1f28b7aa07fc"),
"UserName": "David",
"UserAge": 22,
"UserFavouriteSubject": ["C", "Java"]
}
{
"_id": ObjectId("5c8a96306cea1f28b7aa07fd"),
"UserName": "Bob",
"UserAge": 24,
"UserFavouriteSubject": ["MongoDB", "MySQL"]
}
Example: Find Documents Without UserFavouriteSubject
To find documents that do not have the "UserFavouriteSubject" field ?
db.findDocumentDoNotHaveCertainFields.find({"UserFavouriteSubject": {$exists: false}}).pretty()
{
"_id": ObjectId("5c8a95fb6cea1f28b7aa07fb"),
"UserId": 101,
"UserName": "John",
"UserAge": 21
}
Key Points
-
$exists: falsefinds documents where the field is completely absent -
$exists: truefinds documents where the field exists (even if null) - This operator works with any field type and nested fields
Conclusion
The $exists operator with false value effectively filters documents that are missing specific fields. This is useful for data validation and finding incomplete records in your collection.
Advertisements
