JS Noob
JS Noob

Reputation: 1

MongoDB Aggregation to calculate total revenue by each store for each month

I have a collection named sales with documents structured as follows:-

{

"_id": ObjectId("..."),

"date": ISODate("2024-06-15T00:00:00Z"),

"store": "Store A",

"items": [

     {

         "name": "item1",

         "quantity": 5,

         "price": 10.0

     },

     {

         "name": "item2",

         "quantity": 3,

         "price": 20.0

     }

]
}

How do i calculate the total revenue generated by each store for each month, along with the average price of items sold. The result should be sorted first by store and then by month (in ascending order).

Expected Output:-

[

{

     "store": "Store A",

     "month": "2024-06",

     "totalRevenue": 230.0,

     "averagePrice": 15.0

},

{

     "store": "Store B",

     "month": "2024-06",

     "totalRevenue": 150.0,

     "averagePrice": 12.5

}

]

what i've tried:-

db.sales.aggregate([{
  "$group": {
    "_id" : null,
    "totalRevenue": {
      "$sum": {
        "$multiply": ["$quantity", "$price"]
      }
    },
  }
}]);

update:-

db.sales.aggregate([
  {
    $match: {
      date: { $gte: new ISODate("2024-06-01"), $lt: new ISODate("2024-06-30") },
    },
  },

  {
    $group: {
      month: { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
      totalRevenue: { $sum: { $multiply: ["$price", "$quantity"] } },
      averagePrice: { $avg: "$price" },
    },
  },

  {
    $sort: { totalRevenue: -1 },
  },
]);

Upvotes: 0

Views: 70

Answers (0)

Related Questions