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
How to perform $gt on a hash in a MongoDB document?
The $gt operator selects documents where the value of a field is greater than a specified value. When working with embedded documents (hash/object structures), use dot notation to access nested fields within the $gt query.
Syntax
db.collection.find({
"parentField.nestedField": { $gt: value }
});
Sample Data
db.performQueryDemo.insertMany([
{
"PlayerDetails": {
"PlayerScore": 1000,
"PlayerLevel": 2
},
"PlayerName": "Chris"
},
{
"PlayerDetails": {
"PlayerScore": 0,
"PlayerLevel": 1
},
"PlayerName": "Robert"
},
{
"PlayerDetails": {
"PlayerScore": -10,
"PlayerLevel": 0
},
"PlayerName": "Larry"
},
{
"PlayerDetails": {
"PlayerScore": 1,
"PlayerLevel": 1
},
"PlayerName": "David"
}
]);
Example: Find Players with Score Greater Than 0
Query to retrieve players with a score greater than 0 using $gt on the nested PlayerScore field ?
db.performQueryDemo.find({
"PlayerDetails.PlayerScore": { $gt: 0 }
});
{
"_id" : ObjectId("5cd7eba41a844af18acdffa9"),
"PlayerDetails" : {
"PlayerScore" : 1000,
"PlayerLevel" : 2
},
"PlayerName" : "Chris"
}
{
"_id" : ObjectId("5cd7ebe31a844af18acdffac"),
"PlayerDetails" : {
"PlayerScore" : 1,
"PlayerLevel" : 1
},
"PlayerName" : "David"
}
Key Points
- Use dot notation (
parentField.nestedField) to access fields inside embedded documents. - The
$gtoperator works with numbers, dates, and strings (lexicographic comparison). - Documents with
PlayerScoreof -10 and 0 are excluded as they don't meet the condition.
Conclusion
Use dot notation with $gt to query nested fields in MongoDB documents. This approach allows precise filtering on embedded document properties while maintaining query performance.
Advertisements
