arraysmongodbspring-bootmongotemplategroup

How do I merge arrays from multiple documents without duplicates in MongoDB aggregation?


I have 3 documents:

{
  "id": 1,
  "user": "Brian1",
  "configs": [
    "a",
    "b",
    "c",
    "d"
  ]
}

----

{
  "id": 2,
  "user": "max_en",
  "configs": [
    "a",
    "h",
    "i",
    "j"
  ]
}

----

----

{
  "id": 3,
  "user": "userX",
  "configs": [
    "t",
    "u",
    "s",
    "b"
  ]
}

I want to merge all the "configs" arrays into one array without dublicates,like this:

{
"configs": [
  "a",
  "b",
  "c",
  "d",
  "h",
  "i",
  "j",
  "t",
  "u",
  "s",
  ]
}

I've tried the following:

Aggregation.group("").addToSet("configs").as("configs") and { _id: "", 'configs': { $addToSet: '$configs' } }

The first one gives an error because I've left the fieldname empty (I don't know what to put there).

The second one returns a merged array but with duplicates.


Solution

  • When you want to group all the documents, you need to add {_id: null}

    It means group all documents.

    Probably you need this

    db.collection.aggregate([
      {
        "$unwind": "$configs"
      },
      {
        $group: {
          _id: null,
          configs: {
            "$addToSet": "$configs"
          }
        }
      }
    ])
    

    But be cautious when you need to use on larger collection without a match.