$addToSet (aggregation)
On this page
Definition
-
$addToSet
-
Returns an array of all unique values that results from applying an expression to each document in a group of documents that share the same group by key. Order of the elements in the output array is unspecified.
$addToSet
is only available in the$group
stage.$addToSet
has the following syntax:For more information on expressions, see Expressions.
Behavior
Array Expression
If the value of the expression is an array, $addToSet
appends the whole array as a single element.
Document Expression
If the value of the expression is a document, MongoDB determines that the document is a duplicate if another document in the array matches the to-be-added document exactly; i.e. the existing document has the exact same fields and values in the exact same order.
Memory Restrictions
Starting in 3.6.17, $addToSet
has a memory limit of 100 MiB (100 * 1024 * 1024), even when db.collection.aggregate()
is run with allowDiskUse: true.
See aggregration pipeline limitations for more information.
Example
Consider a sales
collection with the following documents:
Grouping the documents by the day and the year of the date
field, the following operation uses the $addToSet
accumulator to compute the list of unique items sold for each group:
The operation returns the following results: