$inc operator for incrementing in MongoDB - Time & Space Complexity
When using the $inc operator in MongoDB, it is helpful to understand how the time it takes to run changes as the data grows.
We want to know how the cost of incrementing a field changes when there are more documents.
Analyze the time complexity of the following code snippet.
db.collection.updateOne(
{ _id: 123 },
{ $inc: { score: 1 } }
)
This code finds one document by its unique ID and increases its score field by 1.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Searching for the document by its unique ID.
- How many times: This search happens once per update operation.
As the number of documents grows, finding the document by its unique ID stays fast because MongoDB uses an index.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1 search operation |
| 100 | About 1 search operation |
| 1000 | About 1 search operation |
Pattern observation: The time to find and increment does not grow much with more documents because the index keeps it quick.
Time Complexity: O(1)
This means the increment operation takes about the same time no matter how many documents are in the collection.
[X] Wrong: "Incrementing a field with $inc gets slower as the collection grows because it has to check every document."
[OK] Correct: Because the query uses a unique ID and an index, MongoDB finds the document directly without scanning all documents.
Understanding how MongoDB uses indexes to keep updates fast shows you know how databases handle data efficiently, a useful skill in many real projects.
"What if we used updateMany with $inc on a query that matches many documents? How would the time complexity change?"