How to Use $dateToString in Aggregation in MongoDB
Use the
$dateToString operator inside a MongoDB aggregation pipeline to convert a date to a formatted string. Specify the format pattern and the date field to control the output string format.Syntax
The $dateToString operator converts a date to a string in a specified format within an aggregation pipeline.
- date: The date expression to format.
- format: The string pattern to format the date (e.g., "%Y-%m-%d").
- timezone (optional): Timezone to apply to the date.
- onNull (optional): Value to return if the date is null.
json
{
$dateToString: {
date: <dateExpression>,
format: <string>,
timezone: <string>, // optional
onNull: <any> // optional
}
}Example
This example shows how to format a createdAt date field into a string like "2024-06-01" using $dateToString in an aggregation pipeline.
mongodb
db.orders.aggregate([
{
$project: {
orderId: 1,
formattedDate: {
$dateToString: {
format: "%Y-%m-%d",
date: "$createdAt"
}
}
}
}
])Output
[
{ "orderId": 1, "formattedDate": "2024-06-01" },
{ "orderId": 2, "formattedDate": "2024-06-02" }
]
Common Pitfalls
Common mistakes when using $dateToString include:
- Not providing a valid
datefield or expression, resulting in errors or null output. - Using an incorrect
formatstring that does not match MongoDB's date format specifiers. - Ignoring timezone differences, which can cause unexpected date strings.
Always verify the date field exists and use correct format specifiers like %Y for year, %m for month, and %d for day.
json
/* Wrong usage: missing date field */ { $dateToString: { format: "%Y-%m-%d" } } /* Correct usage: include date field */ { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } }
Quick Reference
| Option | Description | Example |
|---|---|---|
| date | The date to format | "$createdAt" |
| format | Date format string | "%Y-%m-%d %H:%M:%S" |
| timezone | Timezone for date conversion | "America/New_York" |
| onNull | Value if date is null | "N/A" |
Key Takeaways
Use $dateToString in aggregation to convert dates to formatted strings.
Always specify the date field and a valid format string.
Consider timezone to get correct date strings.
Check for null dates using the onNull option to avoid missing values.