$setDifference (aggregation)
On this page
Definition
-
$setDifference
-
New in version 2.6.
Takes two sets and returns an array containing the elements that only exist in the first set; i.e. performs a relative complement of the second set relative to the first.
$setDifference
has the following syntax:The arguments can be any valid expression as long as they each resolve to an array. For more information on expressions, see Expressions.
Behavior
$setDifference
performs set operation on arrays, treating arrays as sets. If an array contains duplicate entries, $setDifference
ignores the duplicate entries. $setDifference
ignores the order of the elements.
$setDifference
filters out duplicates in its result to output an array that contain only unique entries. The order of the elements in the output array is unspecified.
If a set contains a nested array element, $setDifference
does not descend into the nested array but evaluates the array at top-level.
Example | Result |
---|---|
Example
Consider an experiments
collection with the following documents:
The following operation uses the $setDifference
operator to return an array of elements found in the B
array but not in the A
array:
The operation returns the following results: