Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
mongoDB mongoose group by month and total sum

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?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!