Business
Jobs
  • About Us
  • Solutions
    • Candidates
      Highly qualified candidates in 48h.
    • Assessments
      500+ technical and psychological assessments, plus anti-fraud system.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Pay in 15+ LATAM countries without setting up a local entity.
  • Pricing
  • Jobs

0

175
Views
MongoDB - Agregación de suma con condicionales

Estoy trabajando en la agregación para realizar algunos análisis en un objeto Orders , quiero obtener el precio total de cada pedido del mes anterior y el total de este mes, intenté pasar el parámetro $match , con las condiciones de tiempo adecuadas pero no está agregando ninguno de los datos. aunque si realizo una consulta de countDocuments de documentos con las mismas condiciones de tiempo, obtengo una cantidad de documentos devueltos.

 const totalThis = await Order.aggregate([ { $match: { // should cut the amount of orders off at the beginning of the current month createdAt: { $gte: thisMonth.getMonth() + 1 }, }, }, { $group: { // using $group, _id has to be there or it doesnt // return anything, though we dont need an _id _id: null, total: { $sum: "$totalPrice", }, }, }, ]); res.status(200).json({ lastMonth: lastMonthSales, thisMonth: thisMonthSales, totalSalesLast: totalLast, totalSalesThis: totalThis, });

En mi solicitud de Postman, lastMonth devuelve 0, por lo que tendría sentido que la matriz devuelta a totalSalesLast estuviera vacía, sin embargo, thisMonth devuelve 5 documentos, por lo que debería funcionar. Obviamente, si elimino el condicional $match , agregará todos los documentos, pero eso es porque está haciendo TODOS los documentos y no filtrando.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Para consultar el documento con createdAt en un mes específico, su etapa $match debe ser la siguiente:

  1. $month : tome el valor del mes de createdAt .
  2. $eq : compara el mes de (1) y el mes de entrada son iguales.
 { $match: { $expr: { $eq: [ { "$month": "$createdAt" }, thisMonth.getMonth() + 1 ] } } }

Ejemplo de parque infantil de Mongo

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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!