Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-
$projectstage creates a new fieldSpecificHourscontaining the hour extracted fromOrderDatetime -
$houroperator returns hour values from 0 (midnight) to 23 (11 PM) -
$matchstage filters documents whereSpecificHoursmatches the specified values -
$inoperator 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.
Advertisements
