Tengo este modelo orderdetails
const model = new Schema( { district: { type: String }, category: String, producer: String, variety: String, qty: String, price: String, subtotal: String, }, { timestamps: true } ); Quiero obtener el informe de ventas mensuales por variety . Primero filtro la variety y luego la agrupo por mes y luego calculo la suma de qty
esta es mi consulta
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", ], }, }, }, ]);Pero la salida viene así.
El resultado de esta consulta es este
[ { _id: { month: 4, qty: 1 }, qty: 1, Month: 'Apr' }, { _id: { month: 4, qty: 5 }, qty: 5, Month: 'Apr' } ]Pero el resultado esperado es un registro con una cantidad total de 6 como este
[ { _id: { month: 4, qty: 6 }, qty: 6, Month: 'Apr' }, ]¿Qué hay de malo en mi consulta?
Dado que la cantidad es para el acumulador, cambie su $group de
{ $group: { _id: { month: { $month: "$createdAt" }, qty: { $sum: { $toInt: "$qty" } } } } }a
{ $group: { _id: { month: { $month: "$createdAt" } }, qty: { $sum: { $toInt: "$qty" } } } }