# Querying Dates in MongoDB: Ranges, Time Zones and ISODate

> How to run a MongoDB query for a date range: half-open $gte/$lt ranges, ISODate in UTC, 'today' in a local time zone, and fixing dates stored as strings.

Source: https://bussolaformongo.app/blog/mongodb-dates-time-zones/ · 2026-11-12

To run a MongoDB query for a date range, use a half-open interval on a field that holds real BSON dates: `{ createdAt: { $gte: ISODate("2026-11-01T00:00:00Z"), $lt: ISODate("2026-12-01T00:00:00Z") } }`. The start is inclusive, the end is exclusive, and both are expressed in UTC, because that is how MongoDB stores every date. Most date bugs come from three places: using `$lte` with an end-of-day guess, forgetting that "today" depends on a time zone, and having dates stored as strings. This article covers each, with `mongosh` examples.

## How MongoDB stores dates

A BSON `Date` is a signed 64-bit integer: milliseconds since the Unix epoch, 1970-01-01T00:00:00Z. There is no time zone attached to the value. When `mongosh` prints `ISODate("2026-11-12T09:30:00.000Z")`, the trailing `Z` means the shell is showing you the UTC rendering of that instant.

Consequences worth remembering:

- Two clients in different countries that insert "the same moment" store the same number.
- The time zone only matters when you convert between an instant and a calendar day or wall-clock time.
- A driver converts its language's date type to and from this integer; what you see in your application depends on that language's local time zone settings, not on anything stored in the database.

You can check the type of a field with `$type`:

```js
db.orders.find({ createdAt: { $type: "date" } }).limit(1)
db.orders.countDocuments({ createdAt: { $not: { $type: "date" } } })
```

The second command counts documents where the field is missing or is not a date, which is a quick way to spot mixed types.

## Constructing dates in mongosh

In `mongosh`, these are equivalent ways to build a date:

```js
ISODate("2026-11-12T00:00:00Z")
new Date("2026-11-12T00:00:00Z")
new Date(Date.UTC(2026, 10, 12))   // months are 0-based in JavaScript
```

Always include the `Z` (or an explicit offset such as `+01:00`). A string without any offset can be interpreted differently depending on the environment, and that is exactly the kind of ambiguity you want to remove from a production query. Note the JavaScript trap in the third form: `Date.UTC(2026, 10, 12)` is November, not October.

If you need the same filter outside the shell, for example in a tool that takes JSON, the Extended JSON form is `{ "$date": "2026-11-12T00:00:00Z" }`.

## Date range queries: use half-open intervals

The reliable pattern is `[start, end)`: `$gte` the start, `$lt` the next boundary.

```js
// All orders created in November 2026 (UTC)
db.orders.find({
  createdAt: {
    $gte: ISODate("2026-11-01T00:00:00Z"),
    $lt:  ISODate("2026-12-01T00:00:00Z")
  }
})
```

Why not `$lte: ISODate("2026-11-30T23:59:59Z")`? Because dates have millisecond precision, a document created at `23:59:59.500Z` falls through the gap. With `$lt` on the next boundary there is no gap and no overlap: consecutive ranges, such as day after day, partition the data exactly, so counts add up.

Other useful shapes:

```js
// Last 24 hours, relative to now
db.orders.find({ createdAt: { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) } })

// Everything before a cutoff
db.logs.find({ ts: { $lt: ISODate("2026-01-01T00:00:00Z") } })

// Documents with no expiry set or an expiry in the past
db.sessions.find({ $or: [{ expiresAt: null }, { expiresAt: { $lt: new Date() } }] })
```

A range on a single date field benefits from an index on that field. If you also sort by it, `.sort({ createdAt: -1 })` can be served from the same index; use `explain("executionStats")` to confirm, as described in [reading explain output](/blog/mongodb-explain-collscan-ixscan/). The operators used here are summarized in the [query operators cheat sheet](/blog/mongodb-query-operators-cheat-sheet/).

## "Today" depends on a time zone

"Orders from today" is not a database concept, it is a calendar concept. For a team in Rome, today in November starts at `2026-11-11T23:00:00Z` (Central European Time is UTC+1 then) and ends 24 hours later. A UTC-midnight filter would put an order placed at 00:30 local time into yesterday.

The simplest approach is to compute the boundaries in your client and pass them as UTC instants:

```js
// Midnight-to-midnight for 2026-11-12 in Europe/Rome (UTC+1 on that date)
db.orders.find({
  createdAt: {
    $gte: ISODate("2026-11-11T23:00:00Z"),
    $lt:  ISODate("2026-11-12T23:00:00Z")
  }
})
```

The offset changes with daylight saving time, so do not hard-code it for a whole year. A day on the date a clock changes is 23 or 25 hours long; computing the two boundaries separately, each with its own offset, handles that correctly.

You can also let the server do the conversion inside an aggregation. The date operators accept a `timezone` option, either an Olson identifier such as `"Europe/Rome"` or a UTC offset such as `"+01:00"`. Olson identifiers handle daylight saving; fixed offsets do not.

```js
db.orders.aggregate([
  { $match: { createdAt: { $gte: ISODate("2026-11-01T00:00:00Z"), $lt: ISODate("2026-12-01T00:00:00Z") } } },
  { $group: {
      _id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt", timezone: "Europe/Rome" } },
      orders: { $sum: 1 }
  } },
  { $sort: { _id: 1 } }
])
```

Keep the `$match` first and expressed on the raw field. That lets MongoDB use an index; wrapping the field in `$dateToString` inside `$match` would force a scan. Daily grouping with `$dateTrunc` (available from MongoDB 5.0) is shown in the [aggregation cheat sheet](/blog/mongodb-aggregation-cheat-sheet/). Other helpers include `$year`, `$month`, `$dayOfMonth`, `$dayOfWeek` and `$hour`, which also accept `timezone` when used as `{ $hour: { date: "$createdAt", timezone: "Europe/Rome" } }`.

### Filtering by calendar fields with $expr

To find, say, every order placed on a Monday in local time, you need an expression:

```js
db.orders.find({
  $expr: { $eq: [ { $dayOfWeek: { date: "$createdAt", timezone: "Europe/Rome" } }, 2 ] }
})
```

`$dayOfWeek` returns 1 for Sunday through 7 for Saturday, so Monday is 2. This works but cannot use an ordinary index on `createdAt` efficiently. Combine it with a range filter on the raw field to limit how many documents get evaluated.

## Dates stored as strings

A common problem: the field looks like a date but is a string, such as `"2026-11-12"` or `"2026-11-12T09:30:00Z"`. A `$gte: ISODate(...)` filter will not match it, because MongoDB compares values of different BSON types by type order, not by meaning.

Diagnose first:

```js
db.orders.aggregate([
  { $group: { _id: { $type: "$createdAt" }, n: { $sum: 1 } } }
])
```

If the result shows `"string"` for some or all documents, you have two options.

**Query the strings as they are.** ISO 8601 strings in a single consistent format sort lexicographically in chronological order, so this works:

```js
db.orders.find({ createdAt: { $gte: "2026-11-01", $lt: "2026-12-01" } })
```

It only holds if every value has the same format and the same time zone. A mix of `"2026-11-1"` and `"2026-11-01"`, or of offsets, breaks the ordering silently.

**Convert them.** Use `$dateFromString` in an aggregation to check the conversion first:

```js
db.orders.aggregate([
  { $match: { createdAt: { $type: "string" } } },
  { $project: { createdAt: 1, parsed: { $dateFromString: { dateString: "$createdAt", onError: null } } } },
  { $match: { parsed: null } },
  { $limit: 20 }
])
```

This lists values that fail to parse. Once the list is empty or understood, an update with a pipeline can convert in place, limited to string values:

```js
db.orders.updateMany(
  { createdAt: { $type: "string" } },
  [ { $set: { createdAt: { $dateFromString: { dateString: "$createdAt" } } } } ]
)
```

If the strings have no offset, `$dateFromString` assumes UTC unless you pass `timezone`. Decide what the original time zone was before you run this on real data, test on a copy or a small filter first, and take a backup. For more on writing updates that change only what you intend, see [updating a document without overwriting it](/blog/update-mongodb-document-without-overwriting/).

## Dates in the app and the driver

Application code adds one more layer. A JavaScript `Date`, a Python `datetime` or a Java `Instant` is converted to a BSON date on write. In Python, naive `datetime` objects are treated as UTC by default and returned naive on read unless you configure `tz_aware`; pass explicit time zones to avoid surprises. If you run quick checks from a phone with a client such as [Bussola](/), you type the same shell syntax, `ISODate("...")` with an explicit `Z`, and get the same UTC semantics as in `mongosh`.

## Checklist

| Situation | Do this |
| --- | --- |
| Range between two instants | `$gte` start, `$lt` end (half-open) |
| Building a date by hand | `ISODate("...Z")` with explicit offset |
| "Today" for local users | Compute local midnight boundaries as UTC instants |
| Grouping per local day | `$dateToString` or `$dateTrunc` with `timezone` as an Olson name |
| Calendar-field filters | `$expr` with `$dayOfWeek` etc., plus a raw range filter |
| Field returns `"string"` from `$type` | Check formats, then `$dateFromString` with `onError` |
| Slow range query | Index the date field, check with `explain("executionStats")` |
