8 Ways to Get the Day from a Date in MongoDB

When extracting the day from a date, the exact option we use will depend on how we want the day to be represented.

For example, do we want the day of the week, the day of the month, or the day of the year? Or perhaps we want it in ISO 8601 format? The return value will usually be different depending on which one we choose.

This article explores those options, and therefore presents 8 ways to return the day 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 day portion from the born field of those documents.

The $dayOfWeek Operator

As the name implies, the $dayOfWeek operator returns the day of the week from a date.

We can run the following code to return the day of the week from the born field in the above document.

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

Result:

{ "birthDayOfWeek" : 1 }
{ "birthDayOfWeek" : 1 }
{ "birthDayOfWeek" : 5 }

It’s also possible to specify the timezone when using the $dayOfWeek operator.

See MongoDB $dayOfWeek for more information and examples.

The $dayOfMonth Operator

The $dayOfMonth operator returns the day of the month from a date.

Example:

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

Result:

{ "birthDayOfMonth" : 3 }
{ "birthDayOfMonth" : 8 }
{ "birthDayOfMonth" : 24 }

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

See MongoDB $dayOfMonth for more information and examples.

The $dayOfYear Operator

Yep, you guessed it. The $dayOfYear operator returns the day of the year from a date.

Example:

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

Result:

{ "birthDayOfYear" : 3 }
{ "birthDayOfYear" : 342 }
{ "birthDayOfYear" : 268 }

The $dayOfYear operator also accepts a timezone parameter.

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

There are format specifiers for each date part, and when it comes to the day portion, you have a choice of format specifiers that will depend on whether you want to return the day of the week, day of month, day of year, or the day of the week in ISO 8601 format.

Example:

db.cats.aggregate(
   [
     {
       $project: {
         _id: 0,
          birthDayOfWeek: { $dateToString: { format: "%w", date: "$born" } },
          birthDayOfMonth: { $dateToString: { format: "%d", date: "$born" } },
          birthDayOfYear: { $dateToString: { format: "%j", date: "$born" } },
          birthDayOfWeekISO: { $dateToString: { format: "%u", date: "$born" } }
       }
     }
   ]
).pretty()

Result:

{
	"birthDayOfWeek" : "1",
	"birthDayOfMonth" : "03",
	"birthDayOfYear" : "003",
	"birthDayOfWeekISO" : "7"
}
{
	"birthDayOfWeek" : "1",
	"birthDayOfMonth" : "08",
	"birthDayOfYear" : "342",
	"birthDayOfWeekISO" : "7"
}
{
	"birthDayOfWeek" : "5",
	"birthDayOfMonth" : "24",
	"birthDayOfYear" : "268",
	"birthDayOfWeekISO" : "4"
}

We could have provided more format specifiers to include other date parts in the result, but seeing as we’re only interested in extracting the day in this article, we only used format specifiers for returning the day portion.

See MongoDB $dateToString for more information and examples.

Also see MongoDB $dateToString Format Specifiers for a list of format specifiers that you can use with $dateToString.

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 can therefore use $dateToParts in one pipeline stage, then add another pipeline stage that extracts the day part if required.

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 day field.

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

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

Result:

{ "birthDay" : 3 }
{ "birthDay" : 8 }
{ "birthDay" : 24 }

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 an option.

It’s also worth mentioning that $dateToParts 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 to return just the day value.

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

Result:

1
0
4

In this case, we use the JavaScript getDay() method, which returns an integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time.

Another option is to use the getUTCDay() method, which uses universal time. We’ll use this method in the next example.

Alternatively, we could have used the JavaScript getDate() method, which returns an integer number, between 1 and 31, representing the day of the month for the given date.

Also, this option returns just the actual day value, and not the whole document, like in the previous examples.

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.getUTCDay();
    return c;
  }
);

Result:

[ 0, 0, 4 ]

As mentioned, the JavaScript getUTCDay() method returns its result using universal time. In this case, it resulted in a different value being returned for the first document (we got 0 in this example, versus 1 in the previous one).

The $isoDayOfWeek Operator

If you need to return the day of week in ISO 8601 format, you can use $isoDayOfWeek. 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,
          birthIsoDayOfWeek: { $isoDayOfWeek: "$born" }
        }
    }
  ]
)

Result:

{ "birthIsoDayOfWeek" : 7 }
{ "birthIsoDayOfWeek" : 7 }
{ "birthIsoDayOfWeek" : 4 }

In this case we get a completely different result than we got when using the $dayOfWeek operator, due to the way ISO 8601 calculates dates.

Here’s an example that demonstrates this difference:

db.cats.aggregate(
  [
    {
      $project:
        {
          _id: 0,
          birthDayOfWeek: { $dayOfWeek: "$born" },
          birthIsoDayOfWeek: { $isoDayOfWeek: "$born" }
        }
    }
  ]
)

Result:

{ "birthDayOfWeek" : 1, "birthIsoDayOfWeek" : 7 }
{ "birthDayOfWeek" : 1, "birthIsoDayOfWeek" : 7 }
{ "birthDayOfWeek" : 5, "birthIsoDayOfWeek" : 4 }