2

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.

TheStranger
  • 1,387
  • 1
  • 13
  • 35

1 Answers1

5

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.

Gibbs
  • 21,904
  • 13
  • 74
  • 138
  • I've just tried `{ 'id': null, 'configs': { $addToSet: '$configs' } }`, I still get duplicates. – TheStranger Jan 27 '22 at 14:49
  • Can you create a mongoPlayground online? It would be easy to understand – Gibbs Jan 27 '22 at 14:50
  • 1
    I'm sorry, but it worked. I was expecting something wrong, sÃ¥ it looked like there was duplicates, but your answer worked perfectly. Thank you ! – TheStranger Jan 27 '22 at 14:57