$dateToString
noun
say it: “DOL-er DAYT too STRING” /ˈdɑlər ˈdeɪt tə ˈstrɪŋ/
A MongoDB aggregation expression that turns a date into text in a chosen format, such as its year and month.
What does $dateToString do in an aggregation pipeline?
$dateToString turns a date into text in the format you give, such as "%Y-%m" for 2026-03, which makes a good key for grouping by month. A timezone such as "America/Denver" reads the date on that clock instead of UTC.
db.orders.aggregate([
{ $group: {
_id: { $dateToString: { format: "%Y-%m", date: "$placedAt", timezone: "America/Denver" } },
orders: { $sum: 1 } } }
]);
// [ { _id: '2026-03', orders: 41 }, { _id: '2026-04', orders: 57 } ]
In a sentence
- “Grouping on $dateToString with "%Y-%m" gave one row of sales per month.”
- “Adding a timezone to $dateToString put the late-evening orders in the right month.”
Level: Journeyman · More MongoDB terms at this level
Updated