Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

101
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda