$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仅在$group阶段可用。

$addToSet has the following syntax:语法如下所示:

{ $addToSet: <expression> }

For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

Behavior行为

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.现有文档具有完全相同的字段和值,顺序完全相同。

Example示例

Consider a sales collection with the following documents:考虑一个sales集合带有以下文档:

{ "_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 to compute the list of unique items sold for each group:按照date字段的日期和年份对文档进行分组,以下操作使用$addToSet累加器计算每个组的唯一销售项目列表:

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" ] }