On this page本页内容
$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
仅在$group
阶段可用。
$addToSet
has the following syntax:语法如下所示:
For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
If the value of the expression is an array, 如果表达式的值是数组,$addToSet
appends the whole array as a single element.$addToSet
将整个数组作为单个元素追加。
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.如果表达式的值是文档,如果数组中的另一个文档与要添加的文档完全匹配,MongoDB将确定该文档是重复的;i、 e.现有文档具有完全相同的字段和值,顺序完全相同。
Consider a 考虑一个sales
collection with the following documents:sales
集合带有以下文档:
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:date
字段的日期和年份对文档进行分组,以下操作使用$addToSet
累加器计算每个组的唯一销售项目列表:
The operation returns the following results:操作返回以下结果: