MongoDB $dateToString Operator

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 4 Examples
Date Operations

What You’ll Learn

The $dateToString operator formats a BSON Date into a text string inside MongoDB aggregation pipelines. Use it for report labels, API responses, CSV exports, or any output where dates must appear in a specific human-readable layout.

01

Format Dates

Date → string.

02

Syntax

date, format.

03

Specifiers

%Y, %m, %d, etc.

04

Timezone

Local display time.

05

Use Cases

Reports, exports.

06

vs $dateFromString

Format vs parse.

Definition and Usage

In MongoDB’s aggregation framework, the $dateToString operator takes a BSON Date and a format pattern and returns a string. For example, formatting ISODate("2024-06-15T14:30:00Z") with format: "%Y-%m-%d" produces "2024-06-15".

💡
Beginner Tip

$dateToString returns a string, not a Date. Both date and format are required. Use timezone when the formatted string should reflect local time rather than UTC.

📝 Syntax

The $dateToString operator takes an object with a required date and format:

mongosh
{
  $dateToString: {
    date: <dateExpression>,
    format: <stringExpression>,
    timezone: <stringExpression>,
    onNull: <stringExpression>
  }
}

Syntax Rules

  • date — required; the BSON date to format (field, $$NOW, or literal).
  • format — required; pattern with format specifiers (e.g. "%Y-%m-%d").
  • timezone — optional Olson timezone ID for local-time formatting.
  • onNull — optional string returned when date is null or missing.
  • Returns a string; use for display only — keep BSON dates for sorting and range queries.

Common Format Specifiers

  • %Y — four-digit year (2024)
  • %m — month 01–12
  • %d — day 01–31
  • %H — hour 00–23 (24-hour clock)
  • %M — minute 00–59
  • %S — second 00–60
  • %L — millisecond 000–999
  • %Z — timezone offset (e.g. +0530)

💡 $dateToString vs $dateFromString vs $dateToParts

$dateToString — BSON Date → formatted text string
$dateFromString — formatted text string → BSON Date
$dateToParts — BSON Date → numeric components (object)

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (date)
Required fieldsdate, format
Return typeString
Format patternUses %Y, %m, %d, etc.
MongoDB version3.6+
ISO date
{
  $dateToString: {
    format: "%Y-%m-%d",
    date: "$createdAt"
  }
}

2024-06-15 style

Date and time
{
  $dateToString: {
    format: "%Y-%m-%d %H:%M",
    date: "$loggedAt"
  }
}

Include hours and minutes

US format
{
  $dateToString: {
    format: "%m/%d/%Y",
    date: "$orderDate"
  }
}

06/15/2024 style

With timezone
{
  $dateToString: {
    format: "%Y-%m-%d %H:%M %Z",
    date: "$eventAt",
    timezone: "America/New_York"
  }
}

Local time display

Examples Gallery

Format order dates for reports, build readable timestamps, show local timezone labels, and handle null dates with $dateToString.

📚 Format a Date as YYYY-MM-DD

Use an orders collection and produce a standard date string from orderDate.

Sample Input Documents

Suppose you have an orders collection with BSON date fields:

mongosh
[
  {
    "_id": ObjectId("609c26812e9274a86871bc6a"),
    "item": "Laptop",
    "orderDate": ISODate("2024-06-15T14:30:00Z")
  },
  {
    "_id": ObjectId("609c26812e9274a86871bc6b"),
    "item": "Mouse",
    "orderDate": ISODate("2024-03-22T09:15:00Z")
  }
]

Example 1 — ISO-Style Date String

Format orderDate as YYYY-MM-DD for CSV export or dashboards:

mongosh
db.orders.aggregate([
  {
    $project: {
      item: 1,
      orderDate: 1,
      orderDateStr: {
        $dateToString: {
          format: "%Y-%m-%d",
          date: "$orderDate"
        }
      }
    }
  }
])

How It Works

  • %Y = four-digit year, %m = zero-padded month, %d = zero-padded day.
  • By default, formatting uses UTC unless you pass timezone.
  • The original orderDate BSON field remains available for sorting and filtering.

📈 Practical Patterns

Readable labels, local timezone display, and null-safe formatting.

Example 2 — Human-Readable Date and Time

Build a full timestamp string for email receipts or log summaries:

mongosh
db.orders.aggregate([
  {
    $project: {
      item: 1,
      receiptLabel: {
        $dateToString: {
          format: "%Y-%m-%d at %H:%M UTC",
          date: "$orderDate"
        }
      }
    }
  }
])

// orderDate: 2024-06-15T14:30:00Z → "2024-06-15 at 14:30 UTC"

How It Works

Literal text in the format string (like " at ") is copied as-is. Combine %Y, %m, %d, and time specifiers to build any fixed-layout timestamp string.

Example 3 — Format in a Local Timezone

Show event times as they appear in Eastern Time for US users:

mongosh
db.events.aggregate([
  {
    $project: {
      title: 1,
      eventAt: 1,
      localDisplay: {
        $dateToString: {
          format: "%Y-%m-%d %H:%M %Z",
          date: "$eventAt",
          timezone: "America/New_York"
        }
      }
    }
  }
])

How It Works

The timezone field shifts how the date is interpreted before formatting. %Z appends the offset. Essential when the same UTC instant should read differently per region.

Example 4 — Handle Missing Dates with onNull

Return a placeholder when optional date fields are null:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      lastLoginDisplay: {
        $dateToString: {
          format: "%Y-%m-%d",
          date: "$lastLogin",
          onNull: "Never logged in"
        }
      }
    }
  }
])

// lastLogin: null → "Never logged in"
// lastLogin: ISODate(...) → formatted date string

How It Works

onNull avoids pipeline errors and gives user-friendly output when dates are optional. Keep the raw lastLogin field for logic; use the formatted string only for display.

🚀 Use Cases

  • Report and dashboard labels — show dates in a consistent readable format.
  • CSV and JSON exports — serialize dates as strings for downstream tools.
  • Email and notification templates — embed formatted timestamps in message bodies.
  • Grouping keys — bucket documents by formatted date strings in $group (prefer BSON dates for performance when possible).

🧠 How $dateToString Works

1

MongoDB resolves the input date

date is evaluated per document — a field, $$NOW, or literal ISODate.

Input
2

$dateToString applies the format

MongoDB maps the date through format specifiers, optionally using timezone.

Format
3

A string is returned

If date is null, onNull provides a fallback; otherwise the formatted text is output.

Output
=

Human-readable date text

Use in exports, UI labels, or alongside $dateFromString for round-trip string conversion.

Conclusion

The $dateToString operator is the standard way to turn BSON dates into formatted text in MongoDB aggregation pipelines. With flexible format specifiers and optional timezone support, it replaces manual string concatenation for display output.

Pair it with $dateFromString when you need to parse strings back into dates, and keep BSON Date fields in your schema for indexing and range queries. Use formatted strings only where human readability matters.

💡 Best Practices

✅ Do

  • Keep BSON dates in the database; format at query time for display
  • Use timezone when users expect local calendar dates
  • Match format to your export or API contract
  • Use onNull for optional date fields in reports
  • Document your format strings for team consistency

❌ Don’t

  • Store dates only as strings if you need range queries or sorting
  • Confuse $dateToString with $dateFromString
  • Forget timezone when displaying local business hours
  • Group on formatted strings when numeric parts from $dateToParts suffice
  • Assume string dates sort correctly without zero-padded %m and %d

Key Takeaways

Knowledge Unlocked

Five things to remember about $dateToString

Use these points when formatting dates as strings in MongoDB.

5
Core concepts
📝 02

Two Required

date, format.

Syntax
🛠 03

String Output

Not a Date type.

Output
🌐 04

Timezone

Local display time.

Option
05

Not $dateFromString

Format vs parse.

Important

❓ Frequently Asked Questions

$dateToString converts a BSON Date into a formatted text string inside aggregation pipelines. Use it for human-readable output, CSV exports, labels in reports, or storing display-friendly date text.
{ $dateToString: { date: <date>, format: <string>, timezone: <string>, onNull: <string> } }. date and format are required. The format string uses specifiers like %Y, %m, and %d.
$dateToString formats a BSON Date into a string. $dateFromString parses a string into a BSON Date. They are inverse operations for text and date conversion.
Common specifiers include %Y (year), %m (month), %d (day), %H (hour), %M (minute), %S (second), and %L (millisecond). Combine them in the format string, e.g. "%Y-%m-%d" for 2024-06-15.
$dateToString is available in MongoDB 3.6 and later in aggregation pipelines and update pipelines that use aggregation expressions.

Continue the Operator Series

Move on to $dateTrunc to truncate dates to period boundaries, or review $dateFromString for the reverse conversion.

Next: $dateTrunc →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful