Working with dates in MongoDB is a common requirement for developers managing time-sensitive data. Whether you’re building analytics dashboards or processing event logs, dates stored as strings need to be converted into MongoDB’s ISODate format for accurate and efficient queries. In this guide, we’ll explore three practical methods to convert strings to dates in MongoDB.
By the end of this article, you’ll understand how to use $toDate
, $dateFromString
, and $convert
to transform string dates into a format that MongoDB can handle seamlessly. We’ll cover real-world examples, common pitfalls, and best practices to ensure your applications run smoothly.
String dates may look similar to ISODate
objects, but MongoDB treats them differently. Converting strings to dates allows you to:
Without proper conversion, you might face errors or unexpected results when querying your data.
$toDate
$toDate
is a simple operator that attempts to convert the input value to a date. It works best with strings in ISO 8601 format.
{
$toDate: <expression>
}
Suppose we have a collection with the following document:
{
"eventDate": "2025-01-16T10:30:00Z"
}
To convert eventDate
to a date object:
db.collection.aggregate([
{
$addFields: {
eventDateISO: { $toDate: "$eventDate" }
}
}
])
{
"eventDate": "2025-01-16T10:30:00Z",
"eventDateISO": ISODate("2025-01-16T10:30:00Z")
}
$dateFromString
$dateFromString
provides more flexibility than $toDate
by allowing custom date formats, time zones, and default values.
{
$dateFromString: {
dateString: <string>,
format: <optional format>,
timezone: <optional timezone>,
onError: <optional value>,
onNull: <optional value>
}
}
For a document:
{
"eventDate": "16-Jan-2025"
}
Convert it using a custom format:
db.collection.aggregate([
{
$addFields: {
eventDateISO: {
$dateFromString: {
dateString: "$eventDate",
format: "%d-%b-%Y"
}
}
}
}
])
{
"eventDate": "16-Jan-2025",
"eventDateISO": ISODate("2025-01-16T00:00:00Z")
}
$convert
$convert
is a versatile operator that can change data types, including strings to dates. It’s particularly useful when working with diverse data formats.
{
$convert: {
input: <expression>,
to: "date",
onError: <optional value>,
onNull: <optional value>
}
}
If the string is in ISO format:
db.collection.aggregate([
{
$addFields: {
eventDateISO: {
$convert: {
input: "$eventDate",
to: "date",
onError: null,
onNull: null
}
}
}
}
])
db.collection.aggregate([
{
$addFields: {
isoDate: { $toDate: "$isoString" }
}
}
])
This example shows how $toDate
can seamlessly handle ISO 8601 strings.
For non-standard formats, $dateFromString
is your go-to solution. Example:
{
date: "01/16/2025"
}
Conversion query:
{
$dateFromString: {
dateString: "$date",
format: "%m/%d/%Y"
}
}
To avoid failures with invalid inputs, use onError
and onNull
options
{
$dateFromString: {
dateString: "$date",
onError: null,
onNull: null
}
}
Group sales data by month:
db.sales.aggregate([
{
$addFields: {
saleDate: { $toDate: "$saleDateString" }
}
},
{
$group: {
_id: { $month: "$saleDate" },
totalSales: { $sum: "$amount" }
}
}
])
Convert strings with time zone awareness:
{
$dateFromString: {
dateString: "$eventDate",
timezone: "America/New_York"
}
}
$toDate
is simple and effective for standard ISO strings.$dateFromString
offers flexibility for custom formats and time zones.$convert
is a versatile tool for type conversion.Converting strings to dates in MongoDB is essential for efficient querying and data manipulation. With $toDate
, $dateFromString
, and $convert
, you can handle various formats and scenarios confidently. By applying the methods discussed here, you’ll unlock MongoDB’s full potential for working with date-based data.
Comments