Introduction to MongoDB $setUnion Operator

$setUnion is an aggregation operator in MongoDB that merges two arrays into a single array and removes duplicates.


The syntax for $setUnion is as follows:

{ $setUnion: [ <array1>, <array2>, ... ] }

Here, <array1> and <array2> are the arrays that need to be merged.

Use Cases

$setUnion can be used in scenarios where we need to merge two arrays into one and remove duplicates, such as:

  • Merging multiple tag arrays into a unique tag list.
  • Merging the friend lists of two users into a unique friend list.


Suppose we have a users collection that stores user data, and each document contains the following fields:

  "_id" : ObjectId("61f3c8e1572a6a846a6a5f0f"),
  "name" : "Alice",
  "hobbies" : [ "reading", "dancing", "travelling" ]

Now, we want to query the hobbies of all users, as well as a unique list of hobbies. We can use the following aggregation pipeline:

    $group: {
      _id: null,
      hobbies: { $push: "$hobbies" }
    $project: {
      _id: 0,
      hobbies: {
        $reduce: {
          input: "$hobbies",
          initialValue: [],
          in: { $setUnion: "$$value" }

In the above aggregation pipeline, we first use $group to put all user hobbies into an array, and then use $reduce and $setUnion to merge these arrays into a unique list of hobbies.

Here are the sample data and results:

Sample Data:

_id name hobbies
ObjectId(“61f3c8e1572a6a846a6a5f0f”) Alice [“reading”, “dancing”, “travelling”]
ObjectId(“61f3c8e2572a6a846a6a5f10”) Bob [“reading”, “painting”]
ObjectId(“61f3c8e3572a6a846a6a5f11”) Carol [“travelling”, “cooking”]

Aggregation Result:

{ "hobbies" : [ "reading", "dancing", "travelling", "painting", "cooking" ] }


The $setUnion operator is a very useful aggregation operator that can merge multiple arrays into a unique array. It can be applied to many scenarios, such as merging multiple tag arrays, merging multiple friend lists, etc.