Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading