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

202
Vistas
How can I get a sum of sums using MongoDB aggregation?

I would like to get the total (sum) of the totalHoursForYear value. Here is my current aggregation:

const byYear = await this.workHistoryModel.aggregate([
  {
    $group: {
      _id: '$year',
      history: {
        $push: '$$ROOT'
      },
      totalHoursForYear: {
        $sum: {
          $add: [
            { $multiply: ['$eightHourDays', 8] },
            { $multiply: ['$tenHourDays', 10] },
            { $multiply: ['$twelveHourDays', 12] },
          ]
        }
      },
    }
  },
]);

Now I need to get a sum of the totalHoursForYear to get the total for all years. Is this possible? I can't seem to get the syntax correct. When I attempt to add another sum:

$group: {
  ...,
  totalHours: {
    $sum: {
      $add: '$totalHoursForYear'
    },
    $push: '$$ROOT'
  }
}

I get an error: "The field 'totalHours' must specify one accumulator"

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

When you need total sum, you can do another $group with _id:null which means to consider all documents

With your script, add the following to get the total and get the same structure.

{
    $group: {
      _id: null,
      data: {
        $push: "$$ROOT"
      },
      total: {
        $sum: "$totalHoursForYear"
      }
    }
  },
  {
    "$unwind": "$data"
  },
  {
    "$addFields": {
      _id: "$data._id",
      history: "$data.history",
      totalHoursForYear: "$data.totalHoursForYear",
      _id: "$$REMOVE",
      data: "$$REMOVE"
    }
  }

Working Mongo playground

over 4 years ago · Santiago Trujillo 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