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.
MongoDB stores dates as ISODate objects, which are ideal for calculations and comparisons. However, converting these dates into strings can be necessary for:
$dateToString
$dateToString
is a powerful operator in the MongoDB Aggregation Framework that lets you format dates as strings based on a customizable pattern.
{
$dateToString: {
format: <string>,
date: <dateExpression>,
timezone: <optional string>,
onNull: <optional string>
}
}
{
"orderDate": ISODate("2025-01-16T10:30:00Z")
}
db.orders.aggregate([
{
$project: {
formattedDate: {
$dateToString: {
format: "%Y-%m-%d",
date: "$orderDate"
}
}
}
}
])
{
"orderDate": ISODate("2025-01-16T10:30:00Z"),
"formattedDate": "2025-01-16"
}
$toString
$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.
{
$toString: <expression>
}
{
"createdAt": ISODate("2025-01-16T10:30:00Z")
}
db.users.aggregate([
{
$project: {
dateAsString: { $toString: "$createdAt" }
}
}
])
{
"createdAt": ISODate("2025-01-16T10:30:00Z"),
"dateAsString": "2025-01-16T10:30:00.000Z"
}
$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.
{
$convert: {
input: <expression>,
to: "string",
onError: <optional value>,
onNull: <optional value>
}
}
{
"eventDate": ISODate("2025-01-16T10:30:00Z")
}
db.events.aggregate([
{
$project: {
stringDate: {
$convert: {
input: "$eventDate",
to: "string",
onError: "Invalid Date",
onNull: "No Date Provided"
}
}
}
}
])
{
"eventDate": ISODate("2025-01-16T10:30:00Z"),
"stringDate": "2025-01-16T10:30:00.000Z"
}
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.
You can customize formats extensively using $dateToString
:
%Y-%m
%Y-%m-%d %H:%M:%S
%d-%b
Add the timezone option to adjust for regional differences:
{
$dateToString: {
format: "%Y-%m-%d %H:%M:%S",
date: "$eventDate",
timezone: "America/New_York"
}
}
Convert and format timestamps for exporting sales reports:
db.sales.aggregate([
{
$project: {
saleDate: {
$dateToString: {
format: "%Y-%m-%d",
date: "$saleTimestamp"
}
}
}
}
])
Use formatted dates to create document keys:
{
$addFields: {
documentKey: {
$concat: [
{ $dateToString: { format: "%Y%m%d", date: "$createdAt" } },
"-",
"$userId"
]
}
}
}
$dateToString
is ideal for customized formatting.$toString
is quick and simple for default ISO 8601 conversions.$convert
offers flexibility for advanced scenarios.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.
Comments