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 $gt operator works with numbers, dates, and strings (lexicographic comparison).
  • Documents with PlayerScore of -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.

Updated on: 2026-03-15T01:20:18+05:30

176 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements