Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group and query by month and day in Mongo DB

I have collection named "orders" and in its documents I have attributes _id, totalAmount and orderTime. I want to get the total amount of orders in a given month ordered by day. Here is the MySQL query for that.(Assuming given month is 9)

SELECT EXTRACT(DAY FROM orderTime) as day, SUM(totalAmount)
FROM orders
where EXTRACT(MONTH FROM orderTime)=9
GROUP BY day;

I need a Mongo query which performs exactly same task. Is there anyway I can achieve this?

like image 999
paarandika Avatar asked Dec 17 '25 05:12

paarandika


1 Answers

Assuming orderTime is a ISODate field, You need to use the aggregation pipeline as below:

  • Project a field for each record to depict its day and month values.
  • Match all the records whose month value = 9.
  • Group by the day field and calculate the sum of the totalAmount field.
  • Then project the required fields.

The Code:

db.orders.aggregate([
{$project:{"totalAmount":1,
           "day":{$dayOfMonth:"$orderTime"},
           "month":{$month:"$orderTime"}}},
{$match:{"month":9}},
{$group:{"_id":"$day",
         "sum":{$sum:"$totalAmount"},
         "day":{$first:"$day"}}},
{$project:{"_id":0,
           "sum":1,
           "day":1}}
])
like image 171
BatScream Avatar answered Dec 20 '25 07:12

BatScream



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!