Search code examples
arraysmongodbaggregation-frameworkaggregation

Merge mongodb arrays in one array with aggregation


I want to display the following result

[
  {
    "MergedTabs": [1,2,3,4,5,6],
    "name": "John"
  }
]

from the collection below

[
  {
    "name":"John",
    "tab":[1,2,3]
  },
  {
    "name":"John",
    "tab":[4,5,6]
  }
]

I tried the query below but I doesn't display what I want

db.collection.aggregate([
  {
    "$group": {
      "_id": "$name",
      "MergedTabs": {
        "$push": "$tab"
      }
    }
  },
    {
    "$project": {
      "name": "$_id",
      "MergedTabs": 1
    }
  }
])

Any ideas how to solve it please ? Thanks


Solution

  •     db.collection.aggregate([
      {
        $unwind: "$tab"
      },
      {
        $group: {
          _id: "$name",
          mergedTab: {
            $push: "$tab"
          }
        }
      },
      {
        $project: {
          name: "$_id",
          mergedTab: 1,
          _id: "$$REMOVE"
        }
      }
    ])