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?"
Practice
{$year: "$dateField"} return when used in an aggregation pipeline?Solution
Step 1: Understand the
The$yearoperator$yearexpression extracts the year component from a date value.Step 2: Apply to the field
UsingdateField{$year: "$dateField"}returns the year number from the date stored indateField.Final Answer:
The year part of the date stored in dateField -> Option BQuick Check:
$yearextracts year [OK]
- Confusing $year with $month or $dayOfMonth
- Expecting a full date string instead of just the year
- Using $year outside aggregation pipeline
createdAt in a MongoDB aggregation pipeline?Solution
Step 1: Identify correct field reference syntax
In MongoDB aggregation, field names must be referenced as strings with a $ prefix, like "$createdAt".Step 2: Confirm correct operator usage
The operator to extract month is$month, so the correct syntax is{ $month: "$createdAt" }.Final Answer:
{ $month: "$createdAt" } -> Option AQuick Check:
Field names need "$" prefix in aggregation [OK]
- Omitting quotes and $ prefix around field name
- Using operator without $ sign
- Passing field name as plain string without $
dateField value of ISODate("2023-07-15T10:00:00Z")?
{ $project: { year: { $year: "$dateField" }, month: { $month: "$dateField" }, day: { $dayOfMonth: "$dateField" } } }Solution
Step 1: Extract year, month, and day from the date
The date is July 15, 2023. So, year = 2023, month = 7 (July), day = 15.Step 2: Confirm output matches extracted values
The output document will have year: 2023, month: 7, day: 15 as projected.Final Answer:
{ year: 2023, month: 7, day: 15 } -> Option CQuick Check:
Date parts match output [OK]
- Assuming months start at 0 instead of 1
- Confusing dayOfMonth with dayOfWeek
- Misreading the date value
orderDate:
{ $project: { day: { $dayOfMonth: orderDate } } }
But it throws an error. What is the mistake?Solution
Step 1: Check field reference syntax inside
Field names must be referenced as strings with a $ prefix, so it should be "$orderDate".$dayOfMonthStep 2: Identify the cause of error
UsingorderDatewithout quotes and $ causes a syntax error in aggregation.Final Answer:
Missing quotes and $ before field name in $dayOfMonth -> Option AQuick Check:
Field names need "$" prefix in aggregation [OK]
- Forgetting $ and quotes around field names
- Assuming $day is a valid operator
- Confusing aggregation stages
saleDate field. Which aggregation pipeline stage correctly groups by year and month using date expressions?Solution
Step 1: Use correct field references with $year and $month
Field names must be referenced as strings with $ prefix, so "$saleDate" is correct.Step 2: Verify grouping keys and sum operator
Grouping by year and month extracted fromsaleDateand summingamountis done correctly in { $group: { _id: { year: { $year: "$saleDate" }, month: { $month: "$saleDate" } }, totalSales: { $sum: "$amount" } } }.Final Answer:
{ $group: { _id: { year: { $year: "$saleDate" }, month: { $month: "$saleDate" } }, totalSales: { $sum: "$amount" } } } -> Option DQuick Check:
Correct field references and operators used [OK]
- Using field names without $ and quotes
- Mixing string field names with expressions
- Incorrectly mixing aggregation operators
Ready to prove it?
Pass the test and this pattern moves unknown
