w3resource

Query MongoDB for Documents Between Two Dates Using $gte and $lte

How to Query MongoDB for Documents between two Dates?

To query for documents with dates between two specified dates in MongoDB, you can use the $gte (greater than or equal) and $lte (less than or equal) operators. This is useful for retrieving data within a particular date range, such as finding records created within the last week, month, or other specific periods.

In MongoDB, you can find documents with a date field that falls between two specific dates using $gte and $lte in your query. This approach is commonly used in applications that need to filter data based on date ranges, like analytics or time-based records. MongoDB stores dates as ISODate objects, making it easy to perform comparisons with specific date boundaries.

Syntax:

The syntax to query documents between two dates is:

db.<collection>.find({
  <date_field>: {
    $gte: ISODate("<start_date>"),
    $lte: ISODate("<end_date>")
  }
})

Explanation:

  • <collection>: The collection to query.
  • <date_field>: The date field in the collection.
  • $gte: ISODate("<start_date>"): Specifies that the date should be greater than or equal to the start date.
  • $lte: ISODate("<end_date>"): Specifies that the date should be less than or equal to the end date.

Example Code:

Here's an example that queries the events collection to find documents where the eventDate falls between January 1, 2023, and December 31, 2023.

Code:

// Query the 'events' collection for records between two dates
db.events.find({
  // Specify the date range condition for 'eventDate'
  eventDate: {
    // Greater than or equal to January 1, 2023
    $gte: ISODate("2023-01-01T00:00:00Z"),
    // Less than or equal to December 31, 2023
    $lte: ISODate("2023-12-31T23:59:59Z")
  }
})

Explanation:

  • db.events.find(...)
    Initiates a query in the events collection to find records based on date criteria.
  • eventDate: { $gte: ISODate(...), $lte: ISODate(...) }
    Specifies a range for the eventDate field using $gte and $lte to set the start and end boundaries.
  • $gte: ISODate("2023-01-01T00:00:00Z")
    Filters for documents where eventDate is greater than or equal to January 1, 2023.
  • $lte: ISODate("2023-12-31T23:59:59Z")
    Filters for documents where eventDate is less than or equal to December 31, 2023.

The query returns all documents in events with an eventDate between January 1, 2023, and December 31, 2023. You can adjust the start and end dates as needed to create custom date ranges for querying.

Practical Guides to MongoDB Snippets and Examples.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/mongodb/snippets/how-to-query-mongodb-for-documents-between-two-dates.php