MongoDB can find documents whose date field falls within a chosen period. This example uses mongosh to query a BSON Date field for all of December 2023 in UTC.
Check the field and collection
Connect to the intended database and identify the collection and date field. The example uses events and date; replace them with your own names.
The field must contain BSON Date values. A date stored as a string or MongoDB’s internal Timestamp type needs a different approach.
Query the date range
db.events.find({
date: {
$gte: ISODate("2023-12-01T00:00:00Z"),
$lt: ISODate("2024-01-01T00:00:00Z")
}
});$gte includes the start of 1 December. $lt excludes the start of 1 January, so the query includes the whole of 31 December rather than stopping at midnight at its start.
Check the results
Inspect records near both boundaries. BSON dates represent UTC instants; convert local time boundaries to UTC if the reporting period uses another timezone.
For frequent queries on a large collection, consider an index on the date field after reviewing the application’s query patterns. Creating an index changes the database and can use significant resources, so plan it separately from this read-only query.