0
0
MongoDBquery~5 mins

Arithmetic expressions ($add, $multiply, $divide) in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Arithmetic expressions ($add, $multiply, $divide)
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

Each document requires a fixed number of arithmetic steps.

Input Size (n)Approx. Operations
1030 (3 operations x 10 documents)
100300 (3 operations x 100 documents)
10003000 (3 operations x 1000 documents)

Pattern observation: The total calculations grow directly with the number of documents.

Final Time Complexity

Time Complexity: O(n)

This means the time to compute grows in a straight line as you add more documents.

Common Mistake

[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.

Interview Connect

Understanding how simple arithmetic operations scale helps you explain performance in real database queries clearly and confidently.

Self-Check

"What if we added a nested $map to perform arithmetic on an array inside each document? How would the time complexity change?"