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

94
Vistas
¿Cómo agregar una matriz anidada usando MongoDB?

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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' }, }, }, ]);
about 4 years ago · Juan Pablo Isaza 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