MongoDB: Query with a Date Range?

MongoDB is a popular NoSQL document database that allows users to query data using a date range. This is done by using the $gte and $lte operators to specify the lower and upper bounds of the date range. Additionally, the $in and $nin operators can be used to query for multiple specific dates within the range. By using these operators, users can quickly and easily query their data within the specified date range.


You can use the following basic syntax to perform a query with a date range in MongoDB:

db.collection.find({
    day: {
        $gt: ISODate("2020-01-21"),
        $lt: ISODate("2020-01-24")
    }
})

This particular query will return all documents in the collection where the “day” field is greater than 2020-01-21 and less than 2020-01-24.

Note that $gt indicates “greater than” and $lt indicates “less than.”

You can also use $gte for “greater than or equal” and $lte for “less than or equal.”

The following examples show how to use this syntax in practice with a collection sales with the following documents:

db.sales.insertOne({day: new Date("2020-01-20"), amount: 40})
db.sales.insertOne({day: new Date("2020-01-21"), amount: 32})
db.sales.insertOne({day: new Date("2020-01-22"), amount: 19})
db.sales.insertOne({day: new Date("2020-01-23"), amount: 29})
db.sales.insertOne({day: new Date("2020-01-24"), amount: 35})

Example 1: Find Documents Between Two Dates

We can use the following code to find all documents where the “day” field is between two specific dates:

db.sales.find({
    day: {
        $gt: ISODate("2020-01-21"),
        $lt: ISODate("2020-01-24")
    }
})

This query returns the following two documents:

{ _id: ObjectId("618548bc7529c93ea0b41490"),
  day: 2020-01-22T00:00:00.000Z,
  amount: 19 }

{ _id: ObjectId("618548bc7529c93ea0b41491"),
  day: 2020-01-23T00:00:00.000Z,
  amount: 29 }

Example 2: Find Documents After Specific Date

We can use the following code to find all documents where the “day” field is after a specific date:

db.sales.find({
    day: {
        $gt: ISODate("2020-01-22")
    }
})

This query returns the following two documents:

{ _id: ObjectId("618548bc7529c93ea0b41491"),
  day: 2020-01-23T00:00:00.000Z,
  amount: 29 }

{ _id: ObjectId("618548bc7529c93ea0b41492"),
  day: 2020-01-24T00:00:00.000Z,
  amount: 35 }

Example 3: Find Documents Before Specific Date

We can use the following code to find all documents where the “day” field is before a specific date:

db.sales.find({
    day: {
        $lt: ISODate("2020-01-22")
    }
})

This query returns the following two documents:

{ _id: ObjectId("618548bc7529c93ea0b4148e"),
  day: 2020-01-20T00:00:00.000Z,
  amount: 40 }

{ _id: ObjectId("618548bc7529c93ea0b4148f"),
  day: 2020-01-21T00:00:00.000Z,
  amount: 32 }

Note: You can find the complete documentation for the ISODate() function .

The following tutorials explain how to perform other common queries in MongoDB:

x