MongoDB provides quite a few aggregation pipeline operators for working with dates. This includes operators that extract certain parts of dates, such as the year, month, day, etc.
There are also a couple of MongoDB methods that enable you to iterate through a cursor, and apply a JavaScript function. This therefore allows you to use JavaScript to extract date values and date parts, etc from a field.
This article presents 6 ways to return the year portion from a date in MongoDB.
Sample Data
Suppose we have a collection called cats
with the following documents:
{ "_id" : 1, "name" : "Scratch", "born" : ISODate("2021-01-03T23:30:15.123Z") } { "_id" : 2, "name" : "Meow", "born" : ISODate("2019-12-08T04:00:12Z") } { "_id" : 3, "name" : "Fluffy", "born" : ISODate("2020-09-24T10:30:00Z") }
The following examples demonstrate various options for returning the year portion from the born
field of those documents.
The $year
Operator
The $year
operator is the most obvious choice for extracting the year portion from a date. It is specifically designed to return a document with the year portion of a date.
We can run the following code to return the year from the born
field in the above document.
db.cats.aggregate(
[
{
$project:
{
_id: 0,
birthYear: { $year: "$born" }
}
}
]
)
Result:
{ "birthYear" : 2021 } { "birthYear" : 2019 } { "birthYear" : 2020 }
You can also specify the timezone when using the $year
operator.
See MongoDB $year
for more information and examples.
The $dateToString
Operator
The $dateToString
operator converts a date object to a string according to a user-specified format. The user can therefore specify that just the year portion is returned if required.
There are format specifiers for each date part. The %Y
format specifier returns the year.
Example:
db.cats.aggregate(
[
{
$project: {
_id: 0,
birthYear: { $dateToString: { format: "%Y", date: "$born" } }
}
}
]
)
Result:
{ "birthYear" : "2021" } { "birthYear" : "2019" } { "birthYear" : "2020" }
We could have provided more format specifiers to include date parts in the result, but seeing as we’re only interested in extracting the year in this article, we only used one format specifier.
See MongoDB $dateToString
for more information and examples.
The $dateToParts
Operator
The $dateToParts
operator returns a document that contains the constituent parts of a given BSON Date value as individual properties. The properties returned are year
, month
, day
, hour
, minute
, second
and millisecond
.
Armed with this knowledge, we can use $dateToParts
in one pipeline stage, then add another pipeline stage that extracts the year
part.
Here’s what $dateToParts
returns for our three documents:
db.cats.aggregate(
[
{
$project:
{
_id: 0,
dateParts: { $dateToParts: { date: "$born" } }
}
}
]
).pretty()
Result:
{ "dateParts" : { "year" : 2021, "month" : 1, "day" : 3, "hour" : 23, "minute" : 30, "second" : 15, "millisecond" : 123 } } { "dateParts" : { "year" : 2019, "month" : 12, "day" : 8, "hour" : 4, "minute" : 0, "second" : 12, "millisecond" : 0 } } { "dateParts" : { "year" : 2020, "month" : 9, "day" : 24, "hour" : 10, "minute" : 30, "second" : 0, "millisecond" : 0 } }
This data can be passed to the next stage in the pipeline to extract just the year
field.
Here’s what happens if we add another projection for just the year
field:
db.cats.aggregate(
[
{
$project:
{
_id: 0,
dateParts: { $dateToParts: { date: "$born" } }
}
},
{
$project:
{
birthYear: "$dateParts.year"
}
}
]
)
Result:
{ "birthYear" : 2021 } { "birthYear" : 2019 } { "birthYear" : 2020 }
This is obviously not as concise as using the previous options. However, depending on what you’re doing in your pipeline, this approach could be a handy option.
The $dateToParts
operator also accepts an iso8601
parameter, which modifies the output document to use ISO week date fields.
See MongoDB $dateToParts
for more information and examples.
The forEach()
Method
You can use cursor.forEach()
to iterate through the cursor, using a JavaScript method such as getFullYear()
or getUTCFullYear()
to return just the year value.
db.cats.find().forEach(
function(c) {
print(
c.born.getFullYear()
);
}
);
Result:
2021 2019 2020
The previous options return a whole document that contains a name/value pair. This option returns just the actual year value, and not the whole document.
The map()
Method
The cursor.map()
method applies a function to each document visited by the cursor and combines the values into an array.
Example:
db.cats.find().map(
function(c) {
c = c.born.getFullYear();
return c;
}
);
Result:
[ 2021, 2019, 2020 ]
The $isoWeekYear
Operator
If you need to return the year in ISO 8601 format, use $isoWeekYear
. The ISO 8601 year starts with the Monday of week 1 and ends with the Sunday of the last week.
Example:
db.cats.aggregate(
[
{
$project:
{
_id: 0,
birthIsoWeekYear: { $isoWeekYear: "$born" }
}
}
]
)
Result:
{ "birthIsoWeekYear" : NumberLong(2020) } { "birthIsoWeekYear" : NumberLong(2019) } { "birthIsoWeekYear" : NumberLong(2020) }
Notice that the first year is now 2020 instead of 2021 like in the previous examples. Not all years will be different when using $isoWeekYear
, because it depends on the date in question.