Set Operators
Set math on arrays — difference, intersection, union, and subset checks.
Set operators treat arrays as mathematical sets and perform set operations on them. Duplicate elements within an array are treated as a single element.
Sample Data for This Chapter
db.experiments.insertMany([
{ A: ["red", "blue", "green"], B: ["red", "blue"] },
{ A: ["red", "blue"], B: [] },
{ A: [], B: ["red"] }
]);$setDifference — Elements in A but not in B
Returns all elements that exist in the first array but not in the second.
{ $setDifference: [<array1>, <array2>] }Examples with literals
$setDifference: [["a", "b", "c"], ["b", "a"]]
// → ["c"]
$setDifference: [["a", "b", "a"], ["b", "a"]]
// → [] (all elements of A are in B)
$setDifference: [["a", "b"], [["b", "a"]]]
// → ["a", "b"] (nested array is a different element!)Pipeline example
db.experiments.aggregate([
{
$project: {
_id: 0, A: 1, B: 1,
diff: { $setDifference: ["$A", "$B"] }
}
}
]);Output:
{ A: ["red","blue","green"], B: ["red","blue"], diff: ["green"] }
{ A: ["red","blue"], B: [], diff: ["red","blue"] }
{ A: [], B: ["red"], diff: [] }$setIntersection — Elements in Both A and B
Returns elements that exist in both arrays.
{ $setIntersection: [<array1>, <array2>] }Examples
$setIntersection: [["a", "b", "c"], ["b", "a"]]
// → ["a", "b"]Pipeline example
db.experiments.aggregate([
{
$project: {
A: 1, B: 1,
commonToBoth: { $setIntersection: ["$A", "$B"] }
}
}
]);$setUnion — All Elements from Both Arrays
Returns all distinct elements from both arrays combined.
{ $setUnion: [<array1>, <array2>] }Examples
$setUnion: [["a", "b", "c"], ["b", "a"]]
// → ["a", "b", "c"]
$setUnion: [["a", "b", "a"], []]
// → ["a", "b"]
$setUnion: [["a", "b"], [["b", "a"]]]
// → ["a", "b", ["a", "b"]] ← nested array is its own element!Pipeline example
db.experiments.aggregate([
{
$project: {
union: { $setUnion: ["$A", "$B"] }
}
}
]);$setIsSubset — Is A a Subset of B?
Returns true if every element in the first array also exists in the second array.
{ $setIsSubset: [<array1>, <array2>] }Examples
$setIsSubset: [["a", "b", "c"], ["b", "a"]]
// → false (c is not in the second array)
$setIsSubset: [["b", "a"], ["a", "b", "c"]]
// → true (a and b are both in the second array)
$setIsSubset: [["a", "b", "c"], []]
// → false (nothing is a subset of empty, except empty)Pipeline example
db.experiments.aggregate([
{
$project: {
A: 1, B: 1,
subset: { $setIsSubset: ["$A", "$B"] }
}
}
]);Visual Summary
Quick Reference
| Operator | Returns | Math Notation |
|---|---|---|
$setDifference | Elements in A not in B | A \ B |
$setIntersection | Elements in both A and B | A ∩ B |
$setUnion | All elements from A and B | A ∪ B |
$setIsSubset | Is every element of A in B? | A ⊆ B |
Congratulations! You’ve completed the MongoDB Aggregation Pipeline guide. Return to the Index to review any section.