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

203
Views
¿Cómo puedo obtener una suma de sumas usando la agregación de MongoDB?

Me gustaría obtener el total (suma) del valor totalHoursForYear . Aquí está mi agregación actual:

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

Ahora necesito obtener una suma de totalHoursForYear para obtener el total de todos los años. es posible? Parece que no puedo obtener la sintaxis correcta. Cuando intento agregar otra suma:

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

Recibo un error: "El campo 'totalHours' debe especificar un acumulador"

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Cuando necesite la suma total, puede hacer otro $group con _id:null , lo que significa considerar todos los documentos

Con su script, agregue lo siguiente para obtener el total y obtener la misma estructura.

 { $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" } }

Zona de juegos Mongo en funcionamiento

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