Introduction to MongoDB $minute Operator

The $minute operator is a date operator in MongoDB used to extract the minute portion from a date. It can be used in the $project and $group stages of the aggregation pipeline, as well as in conditional expressions in query operations.

Syntax

The syntax of the $minute operator is as follows:

{ $minute: <dateExpression> }

Here, <dateExpression> is an expression that represents a date and can be a date object, a string that represents a date, or an expression that returns a date.

Use Cases

The $minute operator is mainly used in scenarios where fine filtering or aggregation of dates is required. For example, suppose there is a collection containing order data that includes the order time of each order, and we want to count the number of orders by hour. In this case, we can use the $hour operator to extract the hour of the order time and perform grouping and counting.

Example

Suppose there is a collection named orders that contains the following data:

{
  "_id": 1,
  "order_date": ISODate("2022-03-05T12:30:00Z")
},
{
  "_id": 2,
  "order_date": ISODate("2022-03-05T13:15:00Z")
},
{
  "_id": 3,
  "order_date": ISODate("2022-03-05T14:20:00Z")
}

Now, we want to count the number of orders for each hour. We can use the following aggregation operation:

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

In the above aggregation operation, the $hour operator is first used to extract the hour of the order time of each order as the basis for grouping. Then, the $sum operator is used to sum the number of orders in each group. Finally, the $sort operator is used to sort the results in ascending order by hour.

After executing the above aggregation operation, the following results will be returned:

{
  "_id": 12,
  "count": 1
},
{
  "_id": 13,
  "count": 1
},
{
  "_id": 14,
  "count": 1
}

Conclusion

The $minute operator is a very useful operator in MongoDB for extracting the minute portion from a date, making it easy to perform time-related filtering and aggregation operations. In actual development, it can be used in combination with other date operators according to specific needs to handle date data more flexibly.