OPTIONS

$addToSet (aggregation)

$addToSet

Returns an array of all the values found in the selected field among the documents in that group. Every unique value only appears once in the result set. There is no ordering guarantee for the output documents.

Example

In the mongo shell, insert documents into a collection named products using the following operation:

db.products.insert( [
   { "type" : "phone", "price" : 389.99, "stocked" : 270000 },
   { "type" : "phone", "price" : 376.99 , "stocked" : 97000},
   { "type" : "phone", "price" : 389.99 , "stocked" : 97000},
   { "type" : "chair", "price" : 59.99, "stocked" : 108 }
] )

Use the following db.collection.aggregate() operation in the mongo shell with the $addToSet operator:

db.products.aggregate( {
     $group : {
               _id : "$type",
               price: { $addToSet: "$price" },
               stocked: { $addToSet: "$stocked" },
   } }
)

This aggregation pipeline returns documents grouped on the value of the type field, with sets constructed from the unique values of the price and stocked fields in the input documents. Consider the following aggregation results:

{
        "_id" : "chair",
        "price" : [
                59.99
        ],
        "stocked" : [
                108
        ]
},
{
        "_id" : "phone",
        "price" : [
                376.99,
                389.99
        ],
        "stocked" : [
                97000,
                270000,
        ]
}