Introduction to MongoDB $month Operator
$month
operator is a date operator in MongoDB aggregation pipeline, which extracts the month from a date field and can be used in aggregation operations.
Syntax
The syntax of $month
operator is as follows:
{ $month: <dateExpression> }
Here, <dateExpression>
represents a date expression, which can be a date field in a document or a date object returned by the $dateFromString
operator.
Use Cases
$month
operator is commonly used to perform aggregation operations on dates, such as calculating monthly sales, monthly active users, etc.
Example
Suppose we have the following order documents:
{
"_id": 1,
"orderDate": ISODate("2022-02-28T08:00:00Z"),
"total": 100
},
{
"_id": 2,
"orderDate": ISODate("2022-03-05T08:00:00Z"),
"total": 200
},
{
"_id": 3,
"orderDate": ISODate("2022-03-15T08:00:00Z"),
"total": 150
}
We can use $group
and $month
operators to calculate the total sales for each month:
db.orders.aggregate([
{
$group: {
_id: { $month: "$orderDate" },
totalSales: { $sum: "$total" }
}
}
])
After running the above aggregation, it will return the following result:
{ "_id" : 2, "totalSales" : 100 }
{ "_id" : 3, "totalSales" : 350 }
Conclusion
$month
operator is a very useful date operator in MongoDB aggregation pipeline, which helps us perform aggregation operations on dates in documents and obtain more valuable analysis results.