$addToSet (aggregation)
Definition
$addToSet
- Returns an array of all unique values that results from applyingan expression to each document in a group of documents that sharethe same group by key. Order of the elements in the output array isunspecified.
$addToSet
is only available in the$group
stage.
$addToSet
has the following syntax:
- { $addToSet: <expression> }
For more information on expressions, seeExpressions.
Behavior
If the value of the expression is an array, $addToSet
appendsthe whole array as a single element.
If the value of the expression is a document, MongoDB determines thatthe document is a duplicate if another document in the array matchesthe to-be-added document exactly; i.e. the existing document has theexact same fields and values in the exact same order.
Example
Consider a sales
collection with the following documents:
- { "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:00:00Z") }
- { "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-02-03T09:00:00Z") }
- { "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-03T09:05:00Z") }
- { "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-02-15T08:00:00Z") }
- { "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-15T09:12:00Z") }
Grouping the documents by the day and the year of the date
field,the following operation uses the $addToSet
accumulator tocompute the list of unique items sold for each group:
- db.sales.aggregate(
- [
- {
- $group:
- {
- _id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } },
- itemsSold: { $addToSet: "$item" }
- }
- }
- ]
- )
The operation returns the following results:
- { "_id" : { "day" : 46, "year" : 2014 }, "itemsSold" : [ "xyz", "abc" ] }
- { "_id" : { "day" : 34, "year" : 2014 }, "itemsSold" : [ "xyz", "jkl" ] }
- { "_id" : { "day" : 1, "year" : 2014 }, "itemsSold" : [ "abc" ] }