How to search for documents based on the value of adding two properties in MongoDB?

To search for documents based on the value of adding two properties in MongoDB, use the aggregation framework with $add operator to calculate the sum and $match to filter results based on the calculated value.

Syntax

db.collection.aggregate([
    { $project: { totalValue: { $add: ["$field1", "$field2"] } } },
    { $match: { totalValue: { $operator: value } } }
]);

Sample Data

db.searchDocumentsDemo.insertMany([
    {"Value1": 100, "Value2": 560},
    {"Value1": 300, "Value2": 150},
    {"Value1": 400, "Value2": 200},
    {"Value1": 190, "Value2": 210}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd3fe1eedc6604c74817ce9"),
        ObjectId("5cd3fe29edc6604c74817cea"),
        ObjectId("5cd3fe30edc6604c74817ceb"),
        ObjectId("5cd3fe45edc6604c74817cec")
    ]
}

Let's verify our sample data:

db.searchDocumentsDemo.find().pretty();
{
    "_id": ObjectId("5cd3fe1eedc6604c74817ce9"),
    "Value1": 100,
    "Value2": 560
}
{
    "_id": ObjectId("5cd3fe29edc6604c74817cea"),
    "Value1": 300,
    "Value2": 150
}
{
    "_id": ObjectId("5cd3fe30edc6604c74817ceb"),
    "Value1": 400,
    "Value2": 200
}
{
    "_id": ObjectId("5cd3fe45edc6604c74817cec"),
    "Value1": 190,
    "Value2": 210
}

Example: Find Documents Where Sum

Search for documents where the sum of Value1 and Value2 is less than 500:

db.searchDocumentsDemo.aggregate([
    { $project: {totalValue: { $add: ["$Value1", "$Value2"] } } },
    { $match: {totalValue: {$lt: 500 }} }
]);
{ "_id": ObjectId("5cd3fe29edc6604c74817cea"), "totalValue": 450 }
{ "_id": ObjectId("5cd3fe45edc6604c74817cec"), "totalValue": 400 }

How It Works

  • $project creates a new field totalValue by adding Value1 and Value2 using $add
  • $match filters documents based on the calculated totalValue
  • The pipeline returns only documents where the sum meets the specified condition

Conclusion

Use MongoDB's aggregation pipeline with $add and $match operators to search documents based on calculated field values. The $project stage computes the sum, and $match filters the results.

Updated on: 2026-03-15T01:10:25+05:30

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements