Home > Back-end >  How to union all values from subdocument in MongoDB 4.0?
How to union all values from subdocument in MongoDB 4.0?

Time:09-22

I'm trying to merge subdocument values ​​into a collection, but I can't seem to find a way to do that. I have the following collection in MongoDB 4.0:

[{
  "_id": "603f8c970f25800300a6c16e",
  "Hash": "vkqsgIPmB4/am4KJkERghDmmCUXEZjrGQxdCF3Fll2brR0YxJSXeTg==",
  "Components": [
    {
      "FieldA": "A-1",
      "FieldB": "B-1"
    },
    {
      "FieldA": "A-2",
      "FieldB": "B-2"
    }
  ]
},
{
  "_id": "609f8c970f25800300a7c16e",
  "Hash": "vkqsgIPmB4/am4KJkERghDmmCUXEZjrGQxdCF3Fll2brR0sddggdTs==",
  "Components": [
    {
      "FieldA": "A-3",
      "FieldB": "B-3"
    },
    {
      "FieldA": "A-4",
      "FieldB": "B-4"
    }
  ]
}]

From this collection I would like to get the following result, where the id would be fed by the value of the main document, and the other fields would be fed by the subdocuments.

[
   {
      "_id":"603f8c970f25800300a6c16e",
      "FieldA":"A-1",
      "FieldB":"B-1"
   },
   {
      "_id":"603f8c970f25800300a6c16e",
      "FieldA":"A-2",
      "FieldB":"B-2"
   },
   {
      "_id":"609f8c970f25800300a7c16e",
      "FieldA":"A-3",
      "FieldB":"B-3"
   },
   {
      "_id":"609f8c970f25800300a7c16e",
      "FieldA":"A-4",
      "FieldB":"B-4"
   }
]

Thanks in advance!

CodePudding user response:

You can do it like this:

  • $unwind - to unwind Components array
  • $project - to project data in the required format
db.collection.aggregate([
  {
    "$unwind": "$Components"
  },
  {
    "$project": {
      "FieldA": "$Components.FieldA",
      "FieldB": "$Components.FieldB"
    }
  }
])

Working example

  • Related