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

99
Vistas
Flatten MongoDB nested object

I have a collection which looks like this:

[
    {
        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,
];

And I'm just calling it with a basic find ie:

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)
})

I need to get the prev sold price into the same level as history.value

ie:

[
    {
        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,
];

So far I've tried the following aggregate call but it's just returning an empty array. Can anyone point me in the right direction please?

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

Thanks,

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

0

Using an aggregation is the right way, here is a working example using $map:

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

Mongo Playground

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