Arithmetic expressions ($add, $multiply, $divide) in MongoDB - Time & Space Complexity
When using arithmetic expressions like $add, $multiply, and $divide in MongoDB, it's important to know how the time to compute results grows as the data size grows.
We want to understand how the number of calculations changes when we process more documents.
Analyze the time complexity of the following MongoDB aggregation snippet.
db.sales.aggregate([
{
$set: {
totalPrice: { $multiply: ["$price", "$quantity"] }
}
},
{
$set: {
discountPrice: { $divide: ["$totalPrice", 2] }
}
},
{
$set: {
finalPrice: { $add: ["$discountPrice", 10] }
}
}
])
This code calculates total, discounted, and final prices for each sale document.
Look for repeated calculations or loops.
- Primary operation: Arithmetic calculations ($multiply, $divide, $add) done once per document.
- How many times: Once for each document in the collection.
Each document requires a fixed number of arithmetic steps.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 30 (3 operations x 10 documents) |
| 100 | 300 (3 operations x 100 documents) |
| 1000 | 3000 (3 operations x 1000 documents) |
Pattern observation: The total calculations grow directly with the number of documents.
Time Complexity: O(n)
This means the time to compute grows in a straight line as you add more documents.
[X] Wrong: "Arithmetic expressions run instantly no matter how many documents there are."
[OK] Correct: Each document needs its own calculations, so more documents mean more work.
Understanding how simple arithmetic operations scale helps you explain performance in real database queries clearly and confidently.
"What if we added a nested $map to perform arithmetic on an array inside each document? How would the time complexity change?"