Home > database >  mongoDB mongoose group by month and total sum
mongoDB mongoose group by month and total sum

Time:04-12

I have this orderdetails model

const model = new Schema(
  {
    district: { type: String },
    category: String,
    producer: String,
    variety: String,
    qty: String,
    price: String,
    subtotal: String,
  },
  { timestamps: true }
);

I want to get the monthly sales report by variety. First I filter the variety and then group it by the month and after calculating the sum of qty

This is my query

 const monthly = await OrderDetails.aggregate([
      {
        $match: {
          variety,
        },
      },
      {
        $group: {
          _id: {
            
            month: { $month: "$createdAt" },
            qty: { $sum: { $toInt: "$qty" } },
          },
        },
      },

      { $sort: { _id: 1 } },
      {
        $project: {
          qty: "$_id.qty",
          Month: {
            $arrayElemAt: [
              [
                "",
                "Jan",
                "Feb",
                "Mar",
                "Apr",
                "May",
                "Jun",
                "Jul",
                "Aug",
                "Sep",
                "Oct",
                "Nov",
                "Dec",
              ],
              "$_id.month",
            ],
          },
        },
      },
    ]);

But the output comes like this

Output for this query is this

[
  { _id: { month: 4, qty: 1 }, qty: 1, Month: 'Apr' },
  { _id: { month: 4, qty: 5 }, qty: 5, Month: 'Apr' }
]

But the expected output is one record with a total qty is 6 like this

[
  { _id: { month: 4, qty: 6 }, qty: 6, Month: 'Apr' },
 
]

What's wrong in my query?

CodePudding user response:

Since qty is for accumulator, change your $group from

  {
    $group: {
      _id: {
        month: { $month: "$createdAt" },
        qty: { $sum: { $toInt: "$qty" } }
      }
    }
  }

to

  {
    $group: {
      _id: { month: { $month: "$createdAt" } },
      qty: { $sum: { $toInt: "$qty" } }
    }
  }

mongoplayground

  • Related