Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

106
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda