$project stage for shaping output in MongoDB - Time & Space Complexity
We want to understand how the time it takes to shape data with the $project stage changes as the data grows.
How does the work grow when we change the number of documents?
Analyze the time complexity of the following code snippet.
db.collection.aggregate([
{ $project: {
name: 1,
age: 1,
isAdult: { $gte: ["$age", 18] }
}}
])
This code shapes each document to only include name, age, and a new field isAdult based on age.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Processing each document once to reshape fields.
- How many times: Once per document in the input collection.
As the number of documents grows, the work grows directly with it because each document is processed once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 operations (one per document) |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: The work increases in a straight line as the number of documents increases.
Time Complexity: O(n)
This means the time to reshape the data grows directly with the number of documents.
[X] Wrong: "The $project stage processes only a few documents quickly, so it runs in constant time regardless of data size."
[OK] Correct: Actually, $project touches every document once, so the time grows as the number of documents grows.
Understanding how $project scales helps you explain how data shaping affects performance in real projects.
What if we added a $match stage before $project to filter documents? How would the time complexity change?