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 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
-
$projectcreates a new fieldtotalValueby adding Value1 and Value2 using$add -
$matchfilters 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.
Advertisements
