$dateToString (Format Date)
Last updated: 2026-10-09
$dateToString (Format Date)
$dateToString formats a date into a string using a format pattern — the standard way to output dates in aggregation pipelines. The pattern uses placeholders like %Y (year), %m (month), %d (day), %H (hour), similar to strftime. When date is null/missing it returns null unless onNull provides a default.
| Category | Date |
|---|---|
| MongoDB Version | 3.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $dateToString: { format: <format>, date: <date-expression>, timezone: <timezone>, onNull: <default> } }
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $dateToString: format order dates
db.orders.aggregate([
{ $project: {
dateStr: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } }
} }
])
Output:
{ "_id": 1, "dateStr": "2026-09-25" }
{ "_id": 2, "dateStr": "2026-09-24" }
📌 Notes
- Placeholders: %Y 4-digit year, %m month, %d day, %H hour, %M minute, %S second
- timezone optional, defaults to UTC; accepts offsets like "+08:00" or IANA zones like "Asia/Shanghai"
- When date is null: returns onNull if set, otherwise null
- MongoDB 6.3+ adds a shorthand format mode
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QHow do I specify a timezone?
AUse IANA names (e.g. "Asia/Shanghai") or UTC offsets (e.g. "+08:00"). Defaults to UTC.
QWhich format specifiers does $dateToString support?
ACommon ones include %Y (year), %m (month), %d (day), %H (hour), %M (minute), %S (second), %L (millisecond), %z (UTC offset) and %j (day of year). See the official docs for the full list.
QWhat happens if the date field is not a Date?
AIt expects a Date; otherwise it returns null or errors (depending on strict mode). Convert with $toDate first if needed.
QCan it output ISO 8601 format?
AYes. Combine %Y-%m-%dT%H:%M:%S.%LZ to produce something like 2026-10-01T08:30:00.000Z; alternatively use the $isoDate expression.