Real Dates, Not Text

You could store a date as text, like "2024-05-12". But text compares letter by letter. "2024-5-12" and "2024-05-12" are the same day, yet they are different text. MongoDB has a real date type for this. In mongosh you create a date with new Date(...).

This course has a screenings collection. Each screening has a date in its when field:

db.screenings.findOne()

Output:

{
  _id: 1,
  film: 'Inception',
  when: ISODate('2024-05-12T00:00:00.000Z')
}

mongosh shows a date as ISODate(...). The Z at the end means the time is in UTC. A date with no time, like new Date("2024-05-12"), means midnight at the start of that day.

Dates work with the comparison operators you already know. These are the screenings in the second half of 2024:

db.screenings.find(
  { when: {
    $gte: new Date("2024-07-01"),
    $lt: new Date("2025-01-01")
  } },
  { _id: 0, film: 1 }
)

Output:

[ { film: 'Parasite' }, { film: 'Whiplash' }, { film: 'Dunkirk' } ]

The range starts on 1 July 2024 and stops just before 1 January 2025. Use $gte for the start and $lt for the end. Then you do not need to know the last day of a month, and a date on the boundary is never counted twice.

new Date() with nothing inside the parentheses gives the current date and time. It is useful when you save the time something happened.

Keep all dates as real dates. The text "2024-07-03" is not equal to the date it looks like, so a query for one will not find the other.

In the exercise, find the screenings in summer 2024.