$addFields for computed fields in MongoDB - Time & Space 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?
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 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.
As the number of documents grows, the work grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 computations of totalPrice |
| 100 | 100 computations of totalPrice |
| 1000 | 1000 computations of totalPrice |
Pattern observation: The work increases directly with the number of documents.
Time Complexity: O(n)
This means the time to add computed fields grows linearly with the number of documents.
[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.
Understanding how operations scale with data size helps you explain your choices clearly and confidently in real projects.
"What if we added multiple computed fields in one $addFields stage? How would the time complexity change?"