Home > Software design >  MongoDB aggregate: unwind and keep roots as seperate documents
MongoDB aggregate: unwind and keep roots as seperate documents

Time:02-22

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.

CodePudding user response:

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

  • Related