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
MongoDB Query to select records having a given key?
To select records having a given key, you can use the $exists operator. This operator checks whether a field exists in the document, regardless of its value.
Syntax
db.collectionName.find({ fieldName: { $exists: true } });
Sample Data
Let's create a collection with sample documents to demonstrate the $exists operator ?
db.selectRecordsHavingKeyDemo.insertMany([
{"StudentName": "John", "StudentAge": 21, "StudentMathMarks": 78},
{"StudentName": "Carol", "StudentMathMarks": 89},
{"StudentName": "Sam", "StudentAge": 26, "StudentMathMarks": 89},
{"StudentName": "Sam", "StudentMathMarks": 98}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c8b7be780f10143d8431e0f"),
ObjectId("5c8b7bfc80f10143d8431e10"),
ObjectId("5c8b7c1280f10143d8431e11"),
ObjectId("5c8b7c2180f10143d8431e12")
]
}
View All Documents
db.selectRecordsHavingKeyDemo.find().pretty();
{
"_id": ObjectId("5c8b7be780f10143d8431e0f"),
"StudentName": "John",
"StudentAge": 21,
"StudentMathMarks": 78
}
{
"_id": ObjectId("5c8b7bfc80f10143d8431e10"),
"StudentName": "Carol",
"StudentMathMarks": 89
}
{
"_id": ObjectId("5c8b7c1280f10143d8431e11"),
"StudentName": "Sam",
"StudentAge": 26,
"StudentMathMarks": 89
}
{
"_id": ObjectId("5c8b7c2180f10143d8431e12"),
"StudentName": "Sam",
"StudentMathMarks": 98
}
Example: Select Records with StudentAge Field
To find all documents that have the StudentAge field ?
db.selectRecordsHavingKeyDemo.find({ StudentAge: { $exists: true } }).pretty();
{
"_id": ObjectId("5c8b7be780f10143d8431e0f"),
"StudentName": "John",
"StudentAge": 21,
"StudentMathMarks": 78
}
{
"_id": ObjectId("5c8b7c1280f10143d8431e11"),
"StudentName": "Sam",
"StudentAge": 26,
"StudentMathMarks": 89
}
Example: Select Records without a Specific Field
To find documents that do NOT have the StudentAge field, use $exists: false ?
db.selectRecordsHavingKeyDemo.find({ StudentAge: { $exists: false } }).pretty();
{
"_id": ObjectId("5c8b7bfc80f10143d8431e10"),
"StudentName": "Carol",
"StudentMathMarks": 89
}
{
"_id": ObjectId("5c8b7c2180f10143d8431e12"),
"StudentName": "Sam",
"StudentMathMarks": 98
}
Conclusion
The $exists operator is useful for filtering documents based on field presence. Use $exists: true to find documents with a field, and $exists: false to find documents without it.
Advertisements
