1

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.

4

1 回答 1

3

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.

于 2022-01-27T14:47:20.507 回答