How to select where sum of fields is greater than a value in MongoDB?

To select documents where the sum of fields is greater than a specific value in MongoDB, use the $expr operator with $add to sum fields and $gt to compare against a threshold value.

Syntax

db.collection.find({
    $expr: {
        $gt: [
            { $add: ["$field1", "$field2", "$field3"] },
            threshold_value
        ]
    }
});

Sample Data

db.sumOfFieldIsGreaterThanDemo.insertMany([
    { "Price1": 10, "Price2": 50, "Price3": 40 },
    { "Price1": 11, "Price2": 1, "Price3": 120 },
    { "Price1": 10, "Price2": 9, "Price3": 6 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cdd84b8bf3115999ed511e6"),
        ObjectId("5cdd84c6bf3115999ed511e7"),
        ObjectId("5cdd84d2bf3115999ed511e8")
    ]
}

Display All Documents

db.sumOfFieldIsGreaterThanDemo.find();
{ "_id": ObjectId("5cdd84b8bf3115999ed511e6"), "Price1": 10, "Price2": 50, "Price3": 40 }
{ "_id": ObjectId("5cdd84c6bf3115999ed511e7"), "Price1": 11, "Price2": 1, "Price3": 120 }
{ "_id": ObjectId("5cdd84d2bf3115999ed511e8"), "Price1": 10, "Price2": 9, "Price3": 6 }

Method 1: Using $expr with $add (Recommended)

Find documents where the sum of Price1, Price2, and Price3 is greater than 100:

db.sumOfFieldIsGreaterThanDemo.find({
    $expr: {
        $gt: [
            { $add: ["$Price1", "$Price2", "$Price3"] },
            100
        ]
    }
});
{ "_id": ObjectId("5cdd84b8bf3115999ed511e6"), "Price1": 10, "Price2": 50, "Price3": 40 }
{ "_id": ObjectId("5cdd84c6bf3115999ed511e7"), "Price1": 11, "Price2": 1, "Price3": 120 }

Method 2: Using $where (Legacy Approach)

db.sumOfFieldIsGreaterThanDemo.find({
    $where: function() {
        return this.Price1 + this.Price2 + this.Price3 > 100;
    }
});
{ "_id": ObjectId("5cdd84b8bf3115999ed511e6"), "Price1": 10, "Price2": 50, "Price3": 40 }
{ "_id": ObjectId("5cdd84c6bf3115999ed511e7"), "Price1": 11, "Price2": 1, "Price3": 120 }

Key Differences

Method Performance Index Usage Recommendation
$expr + $add Better Can use indexes Preferred
$where Slower Cannot use indexes Avoid in production

Conclusion

Use $expr with $add for better performance when summing fields in queries. The $where operator should be avoided as it cannot utilize indexes and executes JavaScript for each document.

Updated on: 2026-03-15T01:24:36+05:30

379 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements