0
0
MongoDBquery~5 mins

$project stage for shaping output in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: $project stage for shaping output
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of documents grows, the work grows directly with it because each document is processed once.

Input Size (n)Approx. Operations
1010 operations (one per document)
100100 operations
10001000 operations

Pattern observation: The work increases in a straight line as the number of documents increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to reshape the data grows directly with the number of documents.

Common Mistake

[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.

Interview Connect

Understanding how $project scales helps you explain how data shaping affects performance in real projects.

Self-Check

What if we added a $match stage before $project to filter documents? How would the time complexity change?