Unwind different arrays in mongodb

28 views Asked by At

Let's assume that I have a MongoDB collection with documents like these:

{
   id: "xyz",
   prop1: "val1",
   prop2: "val2",
   array1: [
       {arr1objid:"1"},
       {arr1objid:"2"},
   ],
   array2: [
       {arr2objid:"a"},
       {arr2objid:"b"},
   ]
}

Is it possible to use some kind of aggregation (maybe something with $unwind) to obtain something like this?

{
   id: "xyz",
   prop1: "val1",
   prop2: "val2",
   array1: {
       arr1objid:"1"
   }
},
{
   id: "xyz",
   prop1: "val1",
   prop2: "val2",
   array1: {
       arr1objid:"2"
   }
},
{
   id: "xyz",
   prop1: "val1",
   prop2: "val2",
   array2: {
       arr2objid:"a"
   }
},
{
   id: "xyz",
   prop1: "val1",
   prop2: "val2",
   array2: {
       arr2objid:"b"
   }
}

Thanks a lot for any suggestion.

1

There are 1 answers

1
Tom Slabbaert On BEST ANSWER

Yes, you should use $facet, it allows you to execute multiple pipelines (one for "array1" and one for array2"), then we just need to merge them

db.collection.aggregate([
  {
    $facet: {
      array1: [
        {
          $unwind: "$array1"
        },
        {
          $project: {
            array2: 0
          }
        }
      ],
      array2: [
        {
          $unwind: "$array2"
        },
        {
          $project: {
            array1: 0
          }
        }
      ],
      
    }
  },
  {
    $project: {
      roots: {
        "$concatArrays": [
          "$array1",
          "$array2"
        ]
      }
    }
  },
  {
    $unwind: "$roots"
  },
  {
    "$replaceRoot": {
      "newRoot": "$roots"
    }
  }
])

Mongo Playground