MongoDB query to find the highest numeric value of a column?

To find the highest numeric value of a column in MongoDB, use $type operator with $not to filter only numeric values, then apply sort() and limit() to get the maximum value.

Syntax

db.collection.find({
    "field": { $not: { $type: "string" } }
}).sort({ "field": -1 }).limit(1);

Sample Data

db.highestNumericValueOfAColumnDemo.insertMany([
    {
        "StudentName": "John",
        "StudentMathMarks": 69
    },
    {
        "StudentName": "Carol",
        "StudentMathMarks": "89"
    },
    {
        "StudentName": "Chris",
        "StudentMathMarks": 82
    },
    {
        "StudentName": "John",
        "StudentMathMarks": "100"
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cba05727219729fde21ddb1"),
        ObjectId("5cba059d7219729fde21ddb2"),
        ObjectId("5cba059d7219729fde21ddb3"),
        ObjectId("5cba059d7219729fde21ddb4")
    ]
}

Example: Find Highest Numeric Value

Let's view all documents first ?

db.highestNumericValueOfAColumnDemo.find().pretty();
{
    "_id": ObjectId("5cba05727219729fde21ddb1"),
    "StudentName": "John",
    "StudentMathMarks": 69
}
{
    "_id": ObjectId("5cba059d7219729fde21ddb2"),
    "StudentName": "Carol",
    "StudentMathMarks": "89"
}
{
    "_id": ObjectId("5cba059d7219729fde21ddb3"),
    "StudentName": "Chris",
    "StudentMathMarks": 82
}
{
    "_id": ObjectId("5cba059d7219729fde21ddb4"),
    "StudentName": "John",
    "StudentMathMarks": "100"
}

Now find the highest numeric value, excluding string values ?

db.highestNumericValueOfAColumnDemo.find({
    StudentMathMarks: { $not: { $type: "string" } }
}).sort({ StudentMathMarks: -1 }).limit(1).pretty();
{
    "_id": ObjectId("5cba059d7219729fde21ddb3"),
    "StudentName": "Chris",
    "StudentMathMarks": 82
}

How It Works

  • { $not: { $type: "string" } } − Excludes string values like "89" and "100"
  • sort({ StudentMathMarks: -1 }) − Sorts in descending order (highest first)
  • limit(1) − Returns only the top result

The query ignores string values "89" and "100", returning only the highest numeric value which is 82.

Conclusion

Use $not with $type: "string" to filter numeric values only, then sort descending and limit to 1 for the highest numeric value. This approach handles mixed data types effectively.

Updated on: 2026-03-15T00:49:21+05:30

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements