query date range in mongodb

Query Date Range in MongoDB

If you want to retrieve documents from MongoDB that fall within a specific date range, you can use the $gte and $lt operators in your query. These operators stand for "greater than or equal to" and "less than", respectively.

Example:

Let's say you have a collection named "orders" that contains documents with a "date" field. You want to retrieve all orders that were placed between January 1st, 2020 and March 31st, 2020.

db.orders.find({
   date: {
      $gte: new Date("2020-01-01"),
      $lt: new Date("2020-04-01")
   }
})

This query will return all documents where the "date" field is greater than or equal to January 1st, 2020 and less than April 1st, 2020.

Multiple Ways to Query Date Range:

  • You can use the $gte and $lt operators as shown in the example above.
  • You can also use the $gt and $lte operators if you want to exclude one or both endpoints of the date range.
  • You can use the $and operator to combine multiple conditions in your query.
  • You can use the Date() constructor to create a new date object in your query.

Example:

db.orders.find({
   $and: [
      { date: { $gte: new Date("2020-01-01") } },
      { date: { $lt: new Date("2020-04-01") } }
   ]
})

This query will return the same results as the first example, but it uses the $and operator to combine the two conditions.

Overall, querying date ranges in MongoDB is straightforward and can be accomplished using a variety of operators and techniques.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe