0
0
MongoDBquery~5 mins

$addFields for computed fields in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: $addFields for computed fields
O(n)
Understanding Time Complexity

We want to understand how the time to add new computed fields changes as the data grows.

How does the number of documents affect the work done by $addFields?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    db.orders.aggregate([
      {
        $addFields: {
          totalPrice: { $multiply: ["$price", "$quantity"] }
        }
      }
    ])
    

This code adds a new field totalPrice to each order by multiplying price and quantity.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The aggregation processes each document once to compute the new field.
  • How many times: Once per document in the collection.
How Execution Grows With Input

As the number of documents grows, the work grows proportionally.

Input Size (n)Approx. Operations
1010 computations of totalPrice
100100 computations of totalPrice
10001000 computations of totalPrice

Pattern observation: The work increases directly with the number of documents.

Final Time Complexity

Time Complexity: O(n)

This means the time to add computed fields grows linearly with the number of documents.

Common Mistake

[X] Wrong: "Adding computed fields with $addFields is instant no matter how many documents there are."

[OK] Correct: Each document must be processed once, so more documents mean more work and more time.

Interview Connect

Understanding how operations scale with data size helps you explain your choices clearly and confidently in real projects.

Self-Check

"What if we added multiple computed fields in one $addFields stage? How would the time complexity change?"