Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading