Introduction to MongoDB $hour Operator

The MongoDB $hour operator is an aggregation operator used to extract the hour portion from a datetime value. In MongoDB, aggregation operators are widely used to perform data aggregation operations on document collections.

Syntax

The syntax of the $hour operator is as follows:

{ $hour: <dateExpression> }

Here, <dateExpression> represents an expression that can be a date object, a date string, or an expression that can be converted to a date.

Use Cases

The $hour operator is typically used in aggregation queries to group, filter, and calculate fields of time type. For example, the $hour operator can be used to find data within a specified time range or to aggregate data by the hour.

Examples

Here’s an example of using the $hour operator. Suppose we have an orders collection, where each document contains an order_time field representing the time the order was created:

{ "_id" : 1, "order_time" : ISODate("2022-03-02T09:23:12.374Z"), "total_amount" : 100 }
{ "_id" : 2, "order_time" : ISODate("2022-03-02T10:34:56.789Z"), "total_amount" : 200 }
{ "_id" : 3, "order_time" : ISODate("2022-03-02T11:45:23.456Z"), "total_amount" : 150 }
{ "_id" : 4, "order_time" : ISODate("2022-03-02T12:56:34.567Z"), "total_amount" : 180 }

To count the number of orders for each hour, you can use the following aggregation query:

db.orders.aggregate([
  {
    $group: {
      _id: { $hour: "$order_time" },
      count: { $sum: 1 }
    }
  }
])

The above aggregation query will yield the following result:

{ "_id" : 9, "count" : 1 }
{ "_id" : 10, "count" : 1 }
{ "_id" : 11, "count" : 1 }
{ "_id" : 12, "count" : 1 }

The above result indicates that there was one order placed at 9am, 10am, 11am, and 12pm, respectively.

Conclusion

The $hour operator is an aggregation operator in MongoDB that can be used to extract the hour portion from a datetime value. It is typically used in aggregation queries to group, filter, and calculate fields of time type. Through the above example, you can see the usage and effect of the $hour operator.