Sling Academy
Home/MongoDB/MongoDB: Using $dateToString to format date time

MongoDB: Using $dateToString to format date time

Last updated: February 03, 2024

Introduction

MongoDB, the popular non-relational database, is known for its flexible schema and powerful querying capabilities. When working with date and time data, presenting it in a human-readable format becomes essential. In MongoDB, the $dateToString aggregation operator enables developers to convert a date object to a string in a specified format.

Understanding $dateToString

The $dateToString operator is part of MongoDB’s aggregation framework and is typically used within an $project or an $addFields stage. Its primary role is to convert Date objects or timestamps to strings according to a user-defined format.

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

In the above example, the format string “%Y-%m-%d” will convert a MongoDB date field named createdAt into the ISO-like string format for date (YYYY-MM-DD).

Basic Usage of $dateToString

To get started with $dateToString, let’s consider a simple collection with documents containing a createdAt field.

db.events.insertMany([
  { name: "Event One", createdAt: new Date() },
  { name: "Event Two", createdAt: new Date() }
]);

Now we can format the createdAt fields as a string.

db.events.aggregate([
  {
    $project: {
      name: 1,
      formattedDate: {
        $dateToString: { format: "%Y-%m-%d", date: "$createdAt" }
      }
    }
  }
]);

Handling Time Zones

Time zones can present a challenge when formatting dates. MongoDB allows the use of timezone option within $dateToString to specify the timezone for conversion.

db.events.aggregate([
  {
    $project: {
      name: 1,
      formattedDate: {
        $dateToString: {
            format: "%Y-%m-%d %H:%M:%S", 
            date: "$createdAt", 
            timezone: "America/New_York"
        }
      }
    }
  }
]);

In this example, times are converted to the Eastern Time zone.

Advanced Formatting

Custom Formats

You can define custom date and time formats using different specifiers.

db.events.aggregate([
  {
    $project: {
      name: 1,
      localTime: {
        $dateToString: { format: "%H:%M:%S", date: "$createdAt" }
      }
    }
  }
]);

This operation extracts only the time portion of the date.

Conditional Formatting

Using $cond, it is possible to apply conditional logic along with date formatting.

db.events.aggregate([
  {
    $project: {
      name: 1,
      formattedDate: {
        $cond: {
            if: { $gte: ["$createdAt", new Date("2021-01-01")] },
            then: {
                $dateToString: { format: "%Y-%m-%d", date: "$createdAt" }
            },
            else: "Before 2021"
        }
      }
    }
  }
]);

Documents with a createdAt date in 2021 or later are formatted, while others get a default string.

Dealing with Null or Missing Dates

It’s important to consider that not all documents may contain date fields, or they might have null values. You can use $ifNull to handle such cases.

db.events.aggregate([
  {
    $project: {
      name: 1,
      formattedDate: {
        $dateToString: {
            format: "%Y-%m-%d", 
            date: { $ifNull: ["$createdAt", new Date()] }
        }
      }
    }
  }
]);

Here, if createdAt is missing or null, the current date is used.

Conclusion

In summary, the $dateToString operator in MongoDB offers powerful capabilities for formatting date and time information. Its flexible syntax can handle a variety of formatting requirements, allowing you to present date data in your applications in a user-friendly manner.

Next Article: MongoDB: Using $dateFromString to convert string to date

Previous Article: How to update a nested array in MongoDB

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)