You have orders, logs or events with a date field, and you need every document from one date up to another. You wrote $gt or $gte with a string, got zero results, or the last day of the range quietly went missing. Both are common, and both come from how MongoDB compares dates.
A MongoDB date range query uses $gte and $lt (or $gt and $lte) on a field stored as a BSON Date, with ISODate() values in mongosh. The pattern that is safe for “between two dates” is: start inclusive, end exclusive, in UTC. Everything below was run against MongoDB 8.0.4 with mongosh 2.14.3, and the C# and Node.js samples were run against the same server. The operators are described in the official $gte reference.
The animation uses six real test documents and shows the mistake that costs most people a day of data.

- Which operator should you use for a date range?
- Prerequisites and test data
- MongoDB date greater than and less than: $gt, $gte, $lt, $lte
- MongoDB query between two dates
- Query one day or today (start-of-day and end-of-day)
- Time zones: MongoDB stores UTC
- String vs Date type: why a date query returns nothing
- Date range in an aggregation $match
- Index the date field and prove it with explain()
- C# MongoDB.Driver: date range filter
- Node.js example
- Common problems and fixes
- Frequently asked questions
- Summary
Which operator should you use for a date range?
$gteand$lt: the default for “between two dates”. The start is included, the end is not, so consecutive ranges never overlap or leave gaps.$gtand$lte: use when the start must be excluded, for example “after the last record I processed”.$ltewith a date only: avoid it for an end date. A value such asISODate("2024-04-30")is midnight, so it drops the rest of that day.- Strings or numbers: only compare them to strings or numbers. MongoDB does not convert a string to a date inside a normal filter.
Prerequisites and test data
- mongosh connected to a MongoDB server (tested on 8.0.4, started locally).
- A field stored as a Date, not as text. The type check is in the pitfalls section below.
These six documents are used for every example. Two sit exactly on the boundaries, one at the last millisecond of March and one at the last millisecond of April:
use("shop");
db.orders.insertMany([
{ _id: 1, ref: "A-1", createdAt: ISODate("2024-03-31T23:59:59.999Z") },
{ _id: 2, ref: "A-2", createdAt: ISODate("2024-04-01T00:00:00.000Z") },
{ _id: 3, ref: "A-3", createdAt: ISODate("2024-04-01T13:45:10.000Z") },
{ _id: 4, ref: "A-4", createdAt: ISODate("2024-04-15T09:30:00.000Z") },
{ _id: 5, ref: "A-5", createdAt: ISODate("2024-04-30T23:59:59.999Z") },
{ _id: 6, ref: "A-6", createdAt: ISODate("2024-05-01T00:00:00.000Z") }
]);
MongoDB date greater than and less than: $gt, $gte, $lt, $lte
Each operator takes a Date. In mongosh use ISODate(); a date without a time means midnight UTC.
db.orders.find({ createdAt: { $gt: ISODate("2024-04-01T00:00:00Z") } }) // after
db.orders.find({ createdAt: { $gte: ISODate("2024-04-01") } }) // on or after
db.orders.find({ createdAt: { $lt: ISODate("2024-04-15T09:30:00Z") } }) // before
db.orders.find({ createdAt: { $lte: ISODate("2024-04-15T09:30:00Z") } }) // on or before
Real results (refs only, from the run):
$gt 2024-04-01T00:00:00Z -> A-3, A-4, A-5, A-6 (A-2 is exactly at the start, so it is excluded)
$gte 2024-04-01 -> A-2, A-3, A-4, A-5, A-6
$lt 2024-04-15T09:30:00Z -> A-1, A-2, A-3
$lte 2024-04-15T09:30:00Z -> A-1, A-2, A-3, A-4
MongoDB query between two dates
Put both operators on the same field object. This returns every April 2024 order:
db.orders.find({
createdAt: { $gte: ISODate("2024-04-01"), $lt: ISODate("2024-05-01") }
})
// A-2, A-3, A-4, A-5
A $lte on the last calendar day looks natural, but it is wrong when the field has a time part:
db.orders.find({
createdAt: { $gte: ISODate("2024-04-01"), $lte: ISODate("2024-04-30") }
})
// A-2, A-3, A-4 <- A-5 (2024-04-30T23:59:59.999Z) is missing
ISODate("2024-04-30") is 2024-04-30T00:00:00Z, so anything later that day is outside the range. Use $lt with the next day instead.
Query one day or today (start-of-day and end-of-day)
The same rule gives a single day: from midnight, up to but not including the next midnight.
db.orders.find({
createdAt: { $gte: ISODate("2024-04-01"), $lt: ISODate("2024-04-02") }
})
// A-2, A-3
For “today” in UTC, build the two boundaries in code. This snippet ran without errors; the count is 0 on the test data because the documents are from 2024:
const start = new Date(); start.setUTCHours(0, 0, 0, 0);
const end = new Date(start.getTime() + 24 * 60 * 60 * 1000);
db.orders.countDocuments({ createdAt: { $gte: start, $lt: end } })
Do not use equality for a date-only value. { createdAt: ISODate("2024-04-01") } matched only A-2, the one document stored at exactly midnight, and missed A-3 at 13:45.
Time zones: MongoDB stores UTC
A BSON Date is an instant stored as milliseconds since the Unix epoch (UTC). Time zones only appear when you build or display values. The same text can mean different instants depending on where it is parsed. On the machine used for these tests, which is on Eastern time (UTC-4 in April):
ISODate("2024-04-01").getTime() // 1711929600000 (UTC midnight)
new Date("2024-04-01").getTime() // 1711929600000 (date-only strings are UTC)
new Date("2024-04-01T00:00:00").getTime() // 1711944000000 (no Z: local time, 4 hours later)
To query a local calendar month, convert the local boundaries to UTC. For April in America/Toronto, midnight is 04:00 UTC. In Toronto, A-2 (00:00Z on April 1) is still March 31 at 20:00, and A-6 (00:00Z on May 1) is still April 30 at 20:00, so the results shift by one document at each end:
const from = new Date(Date.UTC(2024, 3, 1, 4, 0, 0)); // 2024-04-01T04:00:00.000Z
const to = new Date(Date.UTC(2024, 4, 1, 4, 0, 0)); // 2024-05-01T04:00:00.000Z
db.orders.find({ createdAt: { $gte: from, $lt: to } })
// A-3, A-4, A-5, A-6
Fixed offsets break around daylight saving changes. Let the server compute the boundary with $dateFromParts and a named time zone inside $expr:
db.orders.aggregate([
{ $match: { $expr: { $and: [
{ $gte: ["$createdAt", { $dateFromParts: { year: 2024, month: 4, day: 1, timezone: "America/Toronto" } }] },
{ $lt: ["$createdAt", { $dateFromParts: { year: 2024, month: 5, day: 1, timezone: "America/Toronto" } }] }
] } } },
{ $project: { _id: 0, ref: 1 } }
])
// A-3, A-4, A-5, A-6
String vs Date type: why a date query returns nothing
Comparison operators only match values of the same BSON type. If createdAt was inserted as text, a Date filter finds nothing. A copy of the test collection with ISO strings gave:
db.orders_str.countDocuments({ createdAt: { $gte: ISODate("2024-04-01"), $lt: ISODate("2024-05-01") } })
// 0
db.orders.aggregate([{ $group: { _id: { $type: "$createdAt" }, n: { $sum: 1 } } }]) // [ { _id: 'date', n: 6 } ]
db.orders_str.aggregate([{ $group: { _id: { $type: "$createdAt" }, n: { $sum: 1 } } }]) // [ { _id: 'string', n: 6 } ]
Run the $type check first whenever a date query returns zero rows. Then pick one fix:
- Best: convert the data to real dates. See how to change the type of a MongoDB field. Queries stay simple and can use an index.
- Compare strings with strings. UTC ISO 8601 text sorts in date order, so
{ createdAt: { $gte: "2024-04-01", $lt: "2024-05-01" } }returned A-2 to A-5. This only works when every value has the same format and UTC offset. - Convert on the fly with
$exprand$dateFromString, which also returned A-2 to A-5:
db.orders_str.find({ $expr: { $and: [
{ $gte: [ { $dateFromString: { dateString: "$createdAt" } }, ISODate("2024-04-01") ] },
{ $lt: [ { $dateFromString: { dateString: "$createdAt" } }, ISODate("2024-05-01") ] }
] } })
The on-the-fly version converts every document it looks at, so use it for clean-up, not for a hot query path. Details are in the $dateFromString reference.
Date range in an aggregation $match
Put the range in the first $match stage, using the same operators as find, so the index can narrow the input before grouping. This counted April orders per day:
db.orders.aggregate([
{ $match: { createdAt: { $gte: ISODate("2024-04-01"), $lt: ISODate("2024-05-01") } } },
{ $group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } }, n: { $sum: 1 } } },
{ $sort: { _id: 1 } }
])
{ _id: '2024-04-01', n: 2 }
{ _id: '2024-04-15', n: 1 }
{ _id: '2024-04-30', n: 1 }
Index the date field and prove it with explain()
A range query on an unindexed field reads the whole collection. To check, 100,000 documents were inserted five minutes apart starting 2024-01-01, and one day was queried with explain("executionStats"):
const q = { createdAt: { $gte: ISODate("2024-04-01"), $lt: ISODate("2024-04-02") } };
db.big.find(q).explain("executionStats")
// before the index
stage: COLLSCAN
nReturned=288 totalKeysExamined=0 totalDocsExamined=100000
db.big.createIndex({ createdAt: 1 })
// after the index
stage: FETCH -> IXSCAN (index createdAt_1)
nReturned=288 totalKeysExamined=288 totalDocsExamined=288
The same 288 documents come back, but MongoDB reads 288 index entries instead of 100,000 documents. A $expr version of the same range also examined 288 keys in this run. Wrapping the field in a function (for example $dateFromString over a text field) is a different case and was not tested for index use. For compound indexes see creating indexes in MongoDB shell and MongoDB index guidelines. The output format is explained in the explain results reference.
C# MongoDB.Driver: date range filter
Tested on the .NET 10 SDK with MongoDB.Driver 3.14.1 against the same local server and the same six documents. Add the package with dotnet add package MongoDB.Driver --version 3.14.1.
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
var client = new MongoClient("mongodb://127.0.0.1:27099");
var orders = client.GetDatabase("shop").GetCollection<Order>("orders");
var b = Builders<Order>.Filter;
var from = new DateTime(2024, 4, 1, 0, 0, 0, DateTimeKind.Utc);
var to = new DateTime(2024, 5, 1, 0, 0, 0, DateTimeKind.Utc);
// Builders: start inclusive, end exclusive
var filter = b.Gte(o => o.CreatedAt, from) & b.Lt(o => o.CreatedAt, to);
var list = await orders.Find(filter).ToListAsync();
// Same query as LINQ
var linq = await orders.Find(o => o.CreatedAt >= from && o.CreatedAt < to).ToListAsync();
// BsonDocument filter with BsonDateTime
var bson = new BsonDocument("createdAt",
new BsonDocument { { "$gte", new BsonDateTime(from) }, { "$lt", new BsonDateTime(to) } });
var raw = await orders.Find(bson).ToListAsync();
class Order
{
[BsonId] public int Id { get; set; }
[BsonElement("ref")] public string Ref { get; set; } = "";
[BsonElement("createdAt")] public DateTime CreatedAt { get; set; }
}
The rendered filter and the result from the run (builders, LINQ and BsonDocument all returned the same four orders):
filter: { "createdAt" : { "$gte" : { "$date" : "2024-04-01T00:00:00Z" }, "$lt" : { "$date" : "2024-05-01T00:00:00Z" } } }
result: A-2, A-3, A-4, A-5
DateTimeKind decides which instant you query
The driver converts a DateTime to UTC before sending it. A value with Kind=Utc is sent as is. Kind=Unspecified and Kind=Local are both treated as local time. On the Eastern-time machine used here, new DateTime(2024, 4, 1) was sent as 04:00 UTC and the query lost A-2 and picked up A-6:
// 2a Kind=Unspecified, new DateTime(2024, 4, 1) ... new DateTime(2024, 5, 1)
filter: { "createdAt" : { "$gte" : { "$date" : "2024-04-01T04:00:00Z" }, "$lt" : { "$date" : "2024-05-01T04:00:00Z" } } }
result: A-3, A-4, A-5, A-6
// 2b Kind=Local gave the same filter and the same result
On a server set to UTC this difference would not show, which is why it only appears in production. Always build the boundary with DateTimeKind.Utc, or convert a local calendar day explicitly:
var tz = TimeZoneInfo.FindSystemTimeZoneById("America/Toronto");
var startUtc = TimeZoneInfo.ConvertTimeToUtc(new DateTime(2024, 4, 1, 0, 0, 0, DateTimeKind.Unspecified), tz);
var endUtc = TimeZoneInfo.ConvertTimeToUtc(new DateTime(2024, 5, 1, 0, 0, 0, DateTimeKind.Unspecified), tz);
var f = b.Gte(o => o.CreatedAt, startUtc) & b.Lt(o => o.CreatedAt, endUtc);
// $gte 2024-04-01T04:00:00Z, $lt 2024-05-01T04:00:00Z -> A-3, A-4, A-5, A-6
For a DateTimeOffset use .UtcDateTime: b.Lte(o => o.CreatedAt, dto.UtcDateTime) with 2024-04-15T09:30:00Z returned A-1 to A-4. new BsonDateTime(from).MillisecondsSinceEpoch printed 1711929600000, the same value mongosh gives for ISODate("2024-04-01"). More driver patterns are in MongoDB C# date range query.
Node.js example
Tested on Node.js v26.13.1 with the mongodb package 7.9.1. Pass real Date objects, not strings:
import { MongoClient } from "mongodb";
const client = new MongoClient("mongodb://127.0.0.1:27099");
const orders = client.db("shop").collection("orders");
const from = new Date("2024-04-01T00:00:00Z");
const to = new Date("2024-05-01T00:00:00Z");
const rows = await orders.find({ createdAt: { $gte: from, $lt: to } }).sort({ _id: 1 }).toArray();
console.log(rows.map(r => `${r.ref} ${r.createdAt.toISOString()}`).join("\n"));
await client.close();
A-2 2024-04-01T00:00:00.000Z
A-3 2024-04-01T13:45:10.000Z
A-4 2024-04-15T09:30:00.000Z
A-5 2024-04-30T23:59:59.999Z
More Node.js patterns: Node.js MongoDB date time query.
Common problems and fixes
- Zero results: the field is a string, or the filter value is a string. Check with
$typeand compare Date with Date. - The last day is missing: you used
$ltewith a date-only end value. Use$ltwith the next day. - Off by a few hours: a local-time
DateTimeor a string withoutZwas converted using the machine time zone. Build UTC boundaries. - Slow query: run
explain("executionStats").COLLSCANwith a largetotalDocsExaminedmeans the date field needs an index. - Duplicates across batches: use
$gteand$ltso each instant belongs to exactly one range.
Frequently asked questions
How do I query between two dates in MongoDB?
Use $gte for the start and $lt for the next day after the end, on a field stored as a Date: { createdAt: { $gte: ISODate(“2024-04-01”), $lt: ISODate(“2024-05-01”) } }. This includes the whole last day and avoids overlapping ranges.
Why does my MongoDB date query return no results?
The most common cause is a type mismatch: the field is stored as a string, or you compare it to a string, while the other side is a Date. Comparison operators only match the same BSON type. Check the field with $type, then convert the data or use $expr with $dateFromString.
How do I find all records for today in MongoDB?
Build the start of the day and the start of the next day as Date values, then query with $gte and $lt. Decide first whether today means the UTC day or your local day, because MongoDB stores UTC.
Summary
Store dates as BSON Dates, query them with $gte and $lt, and use the next day as the exclusive end so no data at the end of the range is lost. Watch the type (string versus Date) and the time zone (UTC boundaries). Add an index on the date field and confirm it with explain(). Tested here: all mongosh queries on MongoDB 8.0.4, the C# samples on .NET 10 with MongoDB.Driver 3.14.1, and the Node.js sample on mongodb 7.9.1, all on one local server. Not tested: MongoDB Atlas, replica sets or sharded clusters, other server or driver versions, other time zones than Eastern, and index use when a field is wrapped in a function.
Found this useful?
Bookmark this page and share it with your team. Get new .NET, cloud and database tutorials in your inbox.

Seems Typo, pls correct gte = greater than i.e > everywhere is is gte
Thanks Sudhanshu, Corrected it!