MongoDB Query to search for records only in a specific hour?

To search for records only in a specific hour in MongoDB, use the $hour operator within an aggregation pipeline. The $hour operator extracts the hour component (0-23) from a date field.

Syntax

db.collection.aggregate([
    { $project: { fieldName: { $hour: "$dateField" } } },
    { $match: { fieldName: { $in: [hour1, hour2] } } }
]);

Sample Data

db.mongoDbSearchForHoursDemo.insertMany([
    {
        "CustomerName": "Larry",
        "OrderDatetime": new ISODate("2019-01-31 09:45:50")
    },
    {
        "CustomerName": "Larry", 
        "OrderDatetime": new ISODate("2019-02-21 01:10:01")
    },
    {
        "CustomerName": "Larry",
        "OrderDatetime": new ISODate("2019-04-01 04:10:11")
    },
    {
        "CustomerName": "Larry",
        "OrderDatetime": new ISODate("2019-05-11 08:53:01")
    }
]);

View Sample Data

db.mongoDbSearchForHoursDemo.find().pretty();
{
    "_id": ObjectId("5cd6e8a86d78f205348bc62a"),
    "CustomerName": "Larry",
    "OrderDatetime": ISODate("2019-01-31T09:45:50Z")
}
{
    "_id": ObjectId("5cd6e8b86d78f205348bc62b"),
    "CustomerName": "Larry",
    "OrderDatetime": ISODate("2019-02-21T01:10:01Z")
}
{
    "_id": ObjectId("5cd6e8e26d78f205348bc62c"),
    "CustomerName": "Larry",
    "OrderDatetime": ISODate("2019-04-01T04:10:11Z")
}
{
    "_id": ObjectId("5cd6e8f26d78f205348bc62d"),
    "CustomerName": "Larry",
    "OrderDatetime": ISODate("2019-05-11T08:53:01Z")
}

Example: Search Records for Hours 8 and 1

Find all records where OrderDatetime falls within hour 1 (1 AM) or hour 8 (8 AM) ?

db.mongoDbSearchForHoursDemo.aggregate([
    { $project: { SpecificHours: { $hour: "$OrderDatetime" } } },
    { $match: { SpecificHours: { "$in": [1, 8] } } }
]);
{ "_id": ObjectId("5cd6e8b86d78f205348bc62b"), "SpecificHours": 1 }
{ "_id": ObjectId("5cd6e8f26d78f205348bc62d"), "SpecificHours": 8 }

How It Works

  • $project stage creates a new field SpecificHours containing the hour extracted from OrderDatetime
  • $hour operator returns hour values from 0 (midnight) to 23 (11 PM)
  • $match stage filters documents where SpecificHours matches the specified values
  • $in operator allows matching multiple hour values in a single query

Conclusion

Use the $hour operator with aggregation pipelines to filter MongoDB documents by specific hours. This approach efficiently extracts hour components from date fields and enables precise time-based filtering.

Updated on: 2026-03-15T01:17:41+05:30

647 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements