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

101
Views
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 answers
Answer question

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 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!