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

229
Views
MongoDB aggregate: unwind and keep roots as seperate documents

I have want to go from this document:

{
  _id: 1,
  property: "a",
  children: [
    { _id: 2, property: "b" },
    { _id: 3, property: "c" }
  ]
}

to this:

{ _id: 1, property: "a" }
{ _id: 2, property: "b" }
{ _id: 3, property: "c" }

using a MongoDB aggregate function. I have not found anything suitable. $unwind comes the closest, but doesn't quite lead to the desired result.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can do it with Aggregation framework:

  • $concatArrays - to add new property from parent object to the children array
  • $project - to return only children array
  • $unwind - to unwind children array to multiple documents
  • $replaceRoot - to replace to root of the document to the children property
db.collection.aggregate([
  {
    "$project": {
      "_id": 0,
      "children": {
        "$concatArrays": [
          "$children",
          [
            {
              "_id": "$_id",
              "property": "$property"
            }
          ]
        ]
      }
    }
  },
  {
    "$unwind": "$children"
  },
  {
    "$replaceRoot": {
      "newRoot": "$children"
    }
  }
])

Working example

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!