mongodbdatetimeaggregation-frameworkdate-range

Datetime hours range search in mongodb


MongoDB Aggregation - Find Documents within Specific Hour Range and Date I have a MongoDB collection with documents containing an orderDate field of type ISODate. I want to find the documents where the orderDate falls within a specific hour range (e.g., 15:00:00 to 17:59:59) on a given date.

Input : For new Date("2023-06-07T10:30:00Z") from 15:00:00 to 17:59:60

[
  {
    _id: 1,
    orderDate: ISODate("2023-06-07T10:30:00Z"),
    status: "Completed"
  },
  {
    _id: 2,
    orderDate: ISODate("2023-06-07T17:00:00Z"),
    status: "Pending"
  },
  {
    _id: 3,
    orderDate: ISODate("2023-06-07T20:15:00Z"),
    status: "Completed"
  },
  {
    _id: 4,
    orderDate: ISODate("2023-06-08T09:00:00Z"),
    status: "Pending"
  },
  {
    _id: 5,
    orderDate: ISODate("2023-06-08T14:30:00Z"),
    status: "Completed"
  }
]

Output :

[
  {
    "_id": 2,
    "orderDate": ISODate("2023-06-07T17:00:00Z"),
    "status": "Pending"
  }
]

Solution

  • MongoDb Playground : https://mongoplayground.net/p/omFcFgufaBf

    Here $dateFromParts we can use:

    db.collection.aggregate([
      {
        $match: {
          $expr: {
            $and: [
              {
                $gte: [
                  "$orderDate",
                  {
                    $dateFromParts: {
                      year: {
                        $year: new Date("2023-06-07T10:30:00Z")
                      },
                      month: {
                        $month: new Date("2023-06-07T10:30:00Z")
                      },
                      day: {
                        $dayOfMonth: new Date("2023-06-07T10:30:00Z")
                      },
                      hour: 15,
                      minute: 0,
                      second: 0,
                      millisecond: 0
                    }
                  }
                ]
              },
              {
                $lte: [
                  "$orderDate",
                  {
                    $dateFromParts: {
                      year: {
                        $year: new Date("2023-06-07T10:30:00Z")
                      },
                      month: {
                        $month: new Date("2023-06-07T10:30:00Z")
                      },
                      day: {
                        $dayOfMonth: new Date("2023-06-07T10:30:00Z")
                      },
                      hour: 17,
                      minute: 59,
                      second: 60,
                      millisecond: 1000
                    }
                  }
                ]
              }
            ]
          }
        }
      }
    ])