5 Ways to Get the Month from a Date in MongoDB

MongoDB provides a number of aggregation pipeline operators for working with dates, including 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. You can therefore use JavaScript to extract date values and date parts, etc from a field as required.

This article presents 5 ways to return the month 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 month portion from the born field of those documents.

The $month Operator

The $month operator is specifically designed to return a document with the month portion of a given date.

We can run the following code to return the month from the born field in the above document.

db.cats.aggregate(
  [
    {
      $project:
        {
          _id: 0,
          birthMonth: { $month: "$born" }
        }
    }
  ]
)

Result:

{ "birthMonth" : 1 }
{ "birthMonth" : 12 }
{ "birthMonth" : 9 }

You can also specify the timezone when using the $month operator.

See MongoDB $month 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 month portion is returned if required.

There are format specifiers for each date part. The %m format specifier returns the month.

Example:

db.cats.aggregate(
   [
     {
       $project: {
         _id: 0,
          birthMonth: { $dateToString: { format: "%m", date: "$born" } }
       }
     }
   ]
)

Result:

{ "birthMonth" : "01" }
{ "birthMonth" : "12" }
{ "birthMonth" : "09" }

We could have provided more format specifiers to include date parts in the result, but seeing as we’re only interested in extracting the month 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.

We could therefore use $dateToParts in one pipeline stage, then add another pipeline stage that extracts the month 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 result can then be passed to the next stage in the pipeline to extract just the month field.

Here’s what happens if we add another projection for just the month field:

db.cats.aggregate(
  [
    {
      $project:
        {
          _id: 0,
          dateParts: { $dateToParts: { date: "$born" } }
        }
    },
    {
      $project:
        {
          birthMonth: "$dateParts.month"
        }
    }
  ]
)

Result:

{ "birthMonth" : 1 }
{ "birthMonth" : 12 }
{ "birthMonth" : 9 }

This is obviously not as concise as using the previous options. However, depending on what you’re doing in your pipeline, this approach could fit the bill.

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 getMonth() or getUTCMonth() to return just the month value.

db.cats.find().forEach(
  function(c) {
    print(
      c.born.getMonth()
      );
  }
);

Result:

0
11
8

Note that the getMonth() JavaScript method returns the month number as an integer number, between 0 and 11.

You may also notice that the previous options return a whole document that contains a name/value pair, whereas this option returns just the actual month 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.getMonth();
    return c;
  }
);

Result:

[ 0, 11, 8 ] 

Again, we get the months as integers between 0 and 11.