Traté de usar el agregado para averiguar las ventas mensuales de cada producto en mi pedido, pero me encontré con un problema.
Aquí están mis estructuras de datos.
Orden.modelo.ts
const OrderSchema: Schema = new Schema( { userId: { type: String, require: true, }, products: [ { product: { _id: { type: String, }, title: { type: String, }, desc: { type: String, }, img: { type: String, }, categories: { type: Array, }, price: { type: Number, }, createdAt: { type: String, }, updatedAt: { type: String, }, size: { type: String, }, color: { type: String, }, }, quantity: { type: Number, default: 1, }, }, ], quantity: { type: Number, }, total: { type: Number, }, address: { type: String, require: true, }, status: { type: String, default: 'pending', }, }, { timestamps: true }, );Servicio de pedidos.ts
public async getIncome(productId?: string) { const date = new Date(); const lastMonth = new Date(date.setMonth(date.getMonth() - 1)); const previousMonth = new Date(new Date().setMonth(lastMonth.getMonth() - 1)); //const lastYear = new Date(date.setFullYear(date.getFullYear() - 1)); const income = await this.order.aggregate([ { $match: { createdAt: { $gte: lastMonth }, ...(productId && { products: { $elemMatch: { product: { _id: productId } } }, }), }, }, { $project: { month: { $month: '$createdAt' }, sales: '$total', }, }, { $group: { _id: '$month', total: { $sum: '$sales' }, }, }, ]); return income; }Cuando calculé las ventas totales sin productId, salió bien, intenté usar elemMatch para encontrar productId, pero no funcionó, ¿me perdí algo?
Pruebe primero la matriz de "productos" $unwind , luego aplique $match :
const income = await this.order.aggregate([ { $unwind: '$products' }, { $match: { createdAt: { $gte: lastMonth }, product: { _id: productId }, }, }, { $project: { month: { $month: '$createdAt' }, sales: '$total', }, }, { $group: { _id: '$month', total: { $sum: '$sales' }, }, }, ]);