$mul operator for multiplication in MongoDB - Time & Space Complexity
We want to understand how the time it takes to multiply fields in MongoDB grows as the number of documents increases.
How does using the $mul operator affect the work done when updating many records?
Analyze the time complexity of the following code snippet.
db.products.updateMany(
{ category: "books" },
{ $mul: { price: 1.1 } }
)
This code multiplies the price field by 1.1 for all products in the "books" category.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Multiplying the
pricefield for each matching document. - How many times: Once for each document that matches the filter (all "books" products).
As the number of matching documents grows, the total work grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 multiplications |
| 100 | 100 multiplications |
| 1000 | 1000 multiplications |
Pattern observation: Doubling the number of documents doubles the work.
Time Complexity: O(n)
This means the time to complete the multiplication grows linearly with the number of documents updated.
[X] Wrong: "Using $mul updates all documents instantly regardless of count."
[OK] Correct: Each document must be processed individually, so more documents mean more work and more time.
Understanding how update operations scale helps you explain database performance clearly and confidently in real situations.
"What if we added a filter that matches only a fixed number of documents regardless of total size? How would the time complexity change?"