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.