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

624
Views
Aplanar objeto anidado MongoDB

Tengo una colección que se ve así:

 [ { productId: 'c69b7701-c33f-4801-99f3-080450f2b6c7', createdAt: '2021-12-04T17:33:34.221Z', history: [{ value: 304, storePrice: 50, date: 1638639214000, prevSold: { price: 303, createdAt: '2021-12-04T17:32:50.658Z', }, }, ...100 + more records, ], _id: '61aba66d9085f0044f96a700', }, ...100 + more records, ];

Y solo lo estoy llamando con un hallazgo básico, es decir:

 const slug = req.params.slug ProductPrice.find({ productId: slug}).exec((err, data) => { if (err){ return res.status(400).json({ error: errorHandler(err) }) } res.json(data) })

Necesito poner el precio de venta anterior en el mismo nivel que history.value

es decir:

 [ { productId: 'c69b7701-c33f-4801-99f3-080450f2b6c7', createdAt: '2021-12-04T17:33:34.221Z', history: [{ value: 304, storePrice: 50, date: 1638639214000, prevSold: 303, }, ...100 + more records, ], _id: '61aba66d9085f0044f96a700', }, ...100 + more records, ];

Hasta ahora, probé la siguiente llamada agregada, pero solo devuelve una matriz vacía. ¿Puede alguien señalarme en la dirección correcta, por favor?

 ProductPrice.aggregate([ { $match: { productId: slug } }, { $unwind: '$history.prevSold' }, { $addFields: { 'prevSold.value': '$price', }, }, { $replaceRoot: { newRoot: '$prevSold', }, }, ]);

Gracias,

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Usar una agregación es la forma correcta, aquí hay un ejemplo de trabajo usando $map :

 db.collection.aggregate([ { $addFields: { history: { $map: { input: "$history", in: { "$mergeObjects": [ "$$this", { prevSold: "$$this.prevSold.price" } ] } } } } } ])

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