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 if value exists for a field in a MongoDB document?
To check if a value exists for a field in a MongoDB document, you can use the $exists operator with the find() method. This operator checks whether a field exists and optionally whether it contains any values.
Syntax
db.collection.find({ "fieldName": { $exists: true } });
db.collection.find({ "arrayField.0": { $exists: true } });
Sample Data
db.checkIfValueDemo.insertMany([
{
"PlayerName": "John Smith",
"PlayerScores": [5000, 98595858, 554343]
},
{
"PlayerName": "John Doe",
"PlayerScores": []
},
{
"PlayerName": "Carol Taylor",
"PlayerScores": [7848474, 8746345353]
},
{
"PlayerName": "David Miller",
"PlayerScores": []
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cc6f507af8e7a4ca6b2ad98"),
ObjectId("5cc6f512af8e7a4ca6b2ad99"),
ObjectId("5cc6f521af8e7a4ca6b2ad9a"),
ObjectId("5cc6f531af8e7a4ca6b2ad9b")
]
}
Example 1: Check if Array Has Values
To check if the PlayerScores array contains at least one element, query for the existence of the first array element ?
db.checkIfValueDemo.find({"PlayerScores.0": {$exists: true}});
{
"_id": ObjectId("5cc6f507af8e7a4ca6b2ad98"),
"PlayerName": "John Smith",
"PlayerScores": [5000, 98595858, 554343]
}
{
"_id": ObjectId("5cc6f521af8e7a4ca6b2ad9a"),
"PlayerName": "Carol Taylor",
"PlayerScores": [7848474, 8746345353]
}
Example 2: Count Documents with Non-Empty Arrays
db.checkIfValueDemo.find({"PlayerScores.0": {$exists: true}}).count();
2
Key Points
-
$exists: truechecks if a field exists in the document. -
"arrayField.0": {$exists: true}checks if an array has at least one element. - Use
$exists: falseto find documents where a field does not exist.
Conclusion
The $exists operator effectively checks field presence and array content. Use dot notation with array indexes to verify if arrays contain values rather than just existing as empty arrays.
Advertisements
