Date expressions ($year, $month, $dayOfMonth) in MongoDB - Time & Space Complexity
When using date expressions like $year, $month, and $dayOfMonth in MongoDB, it's important to know how the time to run queries changes as data grows.
We want to understand how the work done by these expressions grows when there are more documents to process.
Analyze the time complexity of the following code snippet.
db.orders.aggregate([
{ $project: {
year: { $year: "$orderDate" },
month: { $month: "$orderDate" },
day: { $dayOfMonth: "$orderDate" }
}
}
])
This code extracts the year, month, and day from the orderDate field for each document in the orders collection.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Applying date extraction expressions to each document.
- How many times: Once per document in the collection.
Each document requires the date fields to be extracted once, so the total work grows directly with the number of documents.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 date extractions |
| 100 | 100 date extractions |
| 1000 | 1000 date extractions |
Pattern observation: The work grows in a straight line as the number of documents increases.
Time Complexity: O(n)
This means the time to run the query grows directly in proportion to the number of documents processed.
[X] Wrong: "Using date expressions is instant and does not depend on data size."
[OK] Correct: Each document must be processed individually, so more documents mean more work and longer time.
Understanding how operations scale with data size helps you explain query performance clearly and shows you know how databases handle data internally.
"What if we added a $match stage before $project to filter documents? How would the time complexity change?"