Skip to content

MongoDB Query Using Dates AQSA Spark By {Examples}

  • by

In this article, we will explore examples of MongoDB queries that involve dates. As date types are commonly stored in MongoDB for example insert date, update date, and create date to name a few.

Related:

MongoDB Query Dates by using ISODate

MongoDB Find Objects Between two Dates

Let’s assume the collection student contains the following documents with the date field. I will use this collection to explain how to query MongoDB documents by applying conditions on dates. Note that I use ISODate() to store dates on documents.

# Create Collection with a date fields
db.student.insertMany([
{
“Name”: “Lark Messy”,
“FeeSubmission”: ISODate(“2022-12-30T01:01:22.010Z”)
},
{
“Name”: “Harry Peter”,
“FeeSubmission”: ISODate(“2022-10-23T06:30:22.005Z”)
},
{

“Name”: “Bella Joe”,
“FeeSubmission”: ISODate(“2023-02-09T03:12:15.012Z”)
},
{

“Name”: “Alice Mark”,
“FeeSubmission”: ISODate(“2020-09-15T04:07:05.000Z”)
},
{

“Name”: “Elijah David”,
“FeeSubmission”: ISODate(“2021-01-21T02:11:03.060Z”)
}
]
)

1. To identify the date in the range

Here, the dates are queried to filter documents based on a specific date range, for this, we are using the conditional operators $gt and $lt to perform a MongoDB query.

Consider the following query where the dates are compared using the $gt and $lt operators for the field FeeSubmission. ideally, it finds objects between two dates. These operators are specified with the ISODate() function which creates the date object in the ISO 8601 format, which is the standard format for dates in MongoDB.

Moreover, the documents whose FeeSubmission field lies within the specified range will be retrieved in the result.

#Usage of $gt and $lt operators
# Query between two dates
db.student.find({
FeeSubmission: {
$gt: ISODate(“2020-09-15T04:07:05.000Z”),
$lt: ISODate(“2023-02-09T03:12:15.012Z”)
}
})

The yielded output from the above query.

2. To identify the defined date

Similarly, we can query documents by a specific date by specifying the date to the date function. For example, we query all documents that have a FeeSubmission field equal to the date set in a new Date() function.

# Query fields equals to certain date
db.student.find({ FeeSubmission: new Date(“2021-01-21T02:11:03.060Z”) })

The output displayed the following document which has the same date as given to the Date() function.

More details about the Date() function can be found here.

3. To identify the defined date by month

Alternatively, we can query a date by specifying the month using the $month operator of MongoDB. The $month operator extracts the month from a given date field. Here’s an example where the $expr operator is provided with the $eq operator that matches all documents that have a FeeSubmission field with a month value of 1(January).

#Usage of $month operator
db.student.find({ $expr: { $eq: [{ $month: “$FeeSubmission” }, 1] } })

The document for the month of January is in the following output.

4. To identify the defined date by a year

Next, to query dates by a specific year, we can use the $year operator here. The $year is an aggregation operator that extracts the year from the specified date field.

Consider the following example, we have set the filter expression query.  The FeeSubmission field is set with a year value of 2022. The $year operator extracts the year from the FeeSubmission field, and the $eq operator compares it to the value of 2022.

#Usage of $year operator
db.student.find({ $expr: { $eq: [{ $year: “$FeeSubmission” }, 2022] } })

The output displayed two documents with the year value of 2022.

5. To identify the defined date by a time range

Furthermore, we can also search the dates in MongoDB by a given range of time. We have time operators like $hour, $minute, and $second here.

In the following query, we use the $hour operator to check if the FeeSubmission hour is less than 4. We also use the $minute and $second operators to check if the FeeSubmission field has a minute of 12 and a second value of 15.

#Usage of $hour, $minute, and $second operator
db.student.find({ $expr: { $and: [

    { $lt: [{ $hour: “$FeeSubmission” }, 4] },

    { $eq: [{ $minute: “$FeeSubmission” }, 12] },

    { $eq: [{ $second: “$FeeSubmission” }, 15] }

]}})

The document within the time range date is shown in the following output.

6. To identify the date from the ObjectId field

Finally, we can transform the value to date for querying the data in MongoDB. To accomplish this the $toDate operator is required here.

Here is an example of this, we have deployed the $match stage to filter the documents and select only the documents that have specified _id values. Then, the $in operator is used to match either one of the specified _id values. Next, the $project operator contains the $toDate operator which converts the given _id values to the date.

#Usage if $toDate operator
db.student.aggregate(
  [
    {
      $match: { _id: { $in: [ ObjectId(“6418bc8559c46260c73bd7a1”), ObjectId(“6418bc8559c46260c73bd7a5”) ] } } },
    {
      $project:
        {
          _id: 0,
          “ObjectId”: { $toDate: “$_id” }
        }
    }
  ]

).pretty()

The output shows the _id values are transformed into the date the documents were formed.

7. Conclusion

In conclusion, we covered the different examples significantly that can be used to query dates in MongoDB. By using these examples, the date-based data can be filtered and analyzed with ease.

 In this article, we will explore examples of MongoDB queries that involve dates. As date types are commonly stored in MongoDB for example insert date, update date, and create date to name a few. Related: Let’s assume the collection student contains the following documents with the date field. I will use this collection to explain  Read More MongoDB 

Leave a Reply

Your email address will not be published. Required fields are marked *