;

How to Convert a Date to a String in MongoDB


Tutorialsrack 18/01/2025 MongoDB

Introduction

Dates are a fundamental data type in MongoDB, essential for handling time-sensitive information such as logs, timestamps, and schedules. However, there are scenarios where you need to convert dates into strings, for example, to display formatted dates in user interfaces or to export data.

This article will guide you through 3 effective ways to convert a date to a string in MongoDB using $dateToString, $toString, and $convert. Whether you are a beginner or an advanced user, you’ll learn practical techniques with real-world examples.

Why Convert Dates to Strings in MongoDB?

MongoDB stores dates as ISODate objects, which are ideal for calculations and comparisons. However, converting these dates into strings can be necessary for:

  • Formatting for Frontend Applications: Displaying user-friendly date formats.
  • Exporting Reports: Generating human-readable data for CSV or JSON exports.
  • Creating Custom Keys: Using formatted dates as keys in documents.

Method 1: Using $dateToString

Overview

$dateToString is a powerful operator in the MongoDB Aggregation Framework that lets you format dates as strings based on a customizable pattern.

Syntax

{
  $dateToString: {
    format: <string>,
    date: <dateExpression>,
    timezone: <optional string>,
    onNull: <optional string>
  }
}

Example

Input Document:
{
  "orderDate": ISODate("2025-01-16T10:30:00Z")
}

Query:

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

Output:

{
  "orderDate": ISODate("2025-01-16T10:30:00Z"),
  "formattedDate": "2025-01-16"
}

Method 2: Using $toString

Overview

$toString is a simpler operator that converts dates into their default ISO 8601 string representation. It doesn’t allow customization but is straightforward for standard use cases.

Syntax

{
  $toString: <expression>
}

Example

Input Document:
{
  "createdAt": ISODate("2025-01-16T10:30:00Z")
}

Query:

db.users.aggregate([
  {
    $project: {
      dateAsString: { $toString: "$createdAt" }
    }
  }
])

Output:

{
  "createdAt": ISODate("2025-01-16T10:30:00Z"),
  "dateAsString": "2025-01-16T10:30:00.000Z"
}

Method 3: Using $convert

Overview

$convert is a versatile operator that supports type conversion, including dates to strings. It allows more control, such as specifying fallback values for invalid data.

Syntax

{
  $convert: {
    input: <expression>,
    to: "string",
    onError: <optional value>,
    onNull: <optional value>
  }
}

Example

Input Document:
{
  "eventDate": ISODate("2025-01-16T10:30:00Z")
}

Query:

db.events.aggregate([
  {
    $project: {
      stringDate: {
        $convert: {
          input: "$eventDate",
          to: "string",
          onError: "Invalid Date",
          onNull: "No Date Provided"
        }
      }
    }
  }
])

Output:

{
  "eventDate": ISODate("2025-01-16T10:30:00Z"),
  "stringDate": "2025-01-16T10:30:00.000Z"
}

Detailed Examples with Explanations

Formatting ISO Dates

To display only the date without time:

{
  $dateToString: {
    format: "%Y-%m-%d",
    date: "$timestamp"
  }
}

This ensures that only the year, month, and day are included in the output string.

Customizing Output Formats

You can customize formats extensively using $dateToString:

  • Year and Month Only: %Y-%m
  • Full Date with Time: %Y-%m-%d %H:%M:%S
  • Day and Month Only: %d-%b

Handling Time Zones

Add the timezone option to adjust for regional differences:

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

Real-World Use Cases

Generating Reports

Convert and format timestamps for exporting sales reports:

db.sales.aggregate([
  {
    $project: {
      saleDate: {
        $dateToString: {
          format: "%Y-%m-%d",
          date: "$saleTimestamp"
        }
      }
    }
  }
])

Creating Unique Keys

Use formatted dates to create document keys:

{
  $addFields: {
    documentKey: {
      $concat: [
        { $dateToString: { format: "%Y%m%d", date: "$createdAt" } },
        "-",
        "$userId"
      ]
    }
  }
}

Common Mistakes and How to Avoid Them

  1. Using Incorrect Formats: Ensure the format string matches the desired output structure.
  2. Ignoring Time Zones: Specify the timezone explicitly to avoid discrepancies in global applications.
  3. Not Handling Null Values: Use onNull to provide default values for missing data.

Key Takeaways

  • $dateToString is ideal for customized formatting.
  • $toString is quick and simple for default ISO 8601 conversions.
  • $convert offers flexibility for advanced scenarios.
  • Always consider time zones and handle null or invalid data.

Summary

Converting dates to strings in MongoDB is a crucial skill for developers working with time-sensitive data. Whether you’re building reports, creating keys, or displaying user-friendly formats, understanding $dateToString, $toString, and $convert will help you achieve your goals efficiently. Apply these methods based on your specific needs and ensure robust handling of edge cases for reliable results.


Related Posts



Comments

Recent Posts
Tags