• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:7 mins read
You are currently viewing MongoDB Find Objects Between two Dates

By using find() method you can find objects between two dates in MongoDB, in order to use this to filter dates you have to use ISODate() method to convert the date to ISO format.

Advertisements

Finding objects that fall within a specific date range can be achieved using different operators and methods. In this article, we will discuss how to find objects between two dates and provide examples to demonstrate the process.

1. Syntax to Find Objects Between two Dates in MongoDB

Basically, the $gte and $lte operators in conjunction with the ISODate function to specify the date range is used to find() objects between two dates in MongoDB. The syntax for this query looks like this:


# Syntax
db.sample_collection.find(
{ date: { $gte: ISODate('YYYY-MM-DDTHH:mm:ss.sssZ'), 
          $lte: ISODate('YYYY-MM-DDTHH:mm:ss.sssZ') } 
})

In this case, the date refers to the field that contains the date information. The $gte and $lte operators specify the range of dates to search for, and the ISODate function converts the date string into a valid MongoDB date format.

Now that we know the basic structure of finding objects between two dates, let’s move on to the examples of finding objects between two dates. For this, we have a collection of StudentBlogs where the student blog post with the published date is given.


#Create Collection
db.StudentBlogs.insertMany([
      {
         "_id": 001,
         "name": "Emily Deol",
         "date": ISODate("2022-01-30")
      },
      {
         "_id": 002,
         "name": "Matt Mark",
         "date": ISODate("2022-12-28")
      },
      {
         "_id": 003,
         "name": "Katherina Carl",
         "date": ISODate("2023-02-12")
      }
   ]
)

2. Using the $gte and $lte Operators to Find Between two Dates

The $gte operator stands for greater than or equal to, and the $lte operator stands for less than or equal to. We can use these operators to define a date range and search for objects within that range from MongoDB collection.

To begin with, we want to get all the student blog posts that were published between January 1, 2022, and March 3, 2022. Here’s an example query to accomplish this:


# Usage of $gte and $lte operator
db.StudentBlogs.find({ 
  date: { $gte: new Date("2022-01-01"), 
          $lte: new Date("2023-01-01") 
        } 
  })

Finally, all blog posts published by the students whose date falls within the specified range is obtained in the output.

MongoDB Find objects between two dates

3. By using the $and operator

Additionally, we can use the $and operator to search for objects that meet multiple criteria, including dates. For example, if we want to find all posts that starts between December 12th, 2022, and March 1st, 2023.

We can use the following query where we are using the $and operator to combine two conditions into a single query. These conditions specify the time range using the $gte and $lte operators.


# Using $and operator
db.StudentBlogs.find({
  $and: [
    { date: { $gte: new Date("2022-12-01") } },
    { date: { $lte: new Date("2023-03-01") } }
  ]
})

Therefore, the $and operator fetched the dates between the two specified dates by satisfying the conditions.

You can check more details about $and operator here.

4. By using the $or operator

In addition to the approaches mentioned above, MongoDB also provides the $or operator to construct more complex queries. Let us start by considering an example where we are using the $or operator to combine two separate conditions into a single query.

The first condition specifies the student blog post before January 1, 2023, using the $lt operator, while the second condition specifies the student blog post after December 1, 2023, using the $gt operator.


# Using $or operator
db.StudentBlogs.find({
   $or: [
      { date: { $lt: ISODate("2023-01-01") } },
      { date: { $gt: ISODate("2023-12-01") } }
   ]
})

At last, the output is generated from the above query.

MongoDB Find objects

5. By using the $expr and $month operators

Further, you can also use the $expr operator and the $month aggregation operator. For this purpose, we created a query that will find all blog posts published by the students whose date field falls in the month of January. We use the $month operator to extract the month component of the date field and compare it to the specified month using the $eq operator.


# Using $expr and $month operators
db.StudentBlogs.find({ 
    $expr: { $eq: [ { $month: "$date" }, 1 ] } 
  })

 The output is generated straightaway:

MongoDB Find objects between dates

6. Conclusion

In summary, finding objects between two dates in MongoDB is an important aspect of database operations. By using operators such as $gte, $lte, $and, $or, $expr, and $month, we can easily filter objects based on date ranges. These examples illustrate the flexibility and power of MongoDB’s query language for handling date and time values.

This Post Has One Comment

  1. Sabbir Hossen

    nice presentation…and easy explanations

Comments are closed.