AggregateCommand.addToSet(value: Expression): Object

View Markdown

Last edited on 2026-07-04

Supported on: Mini Program 2.7.4, Cloud Function 0.8.1, Web

Aggregation operator. An aggregation operator. Adds a value to an array. If the value already exists in the array, no action is taken. This can only be used in a group stage.

Parameters

value: Expression

Expression

Return Value

Object

API Description

The addToSet syntax is as follows:

db.command.aggregate.addToSet(<expression>)

The expression is a string in the format $ + specified field. If the value of the specified field is an array, the entire array is treated as a single element.

Sample Code

Assume the records in the passages collection are as follows:

{ "category": "web", "tags": [ "JavaScript", "CSS" ], "title": "title1" }
{ "category": "System", "tags": [ "C++", "C" ], "title": "title2" }

Non-Array Fields

The type of the corresponding value for the category field in each record is not an array. Use addToSet to collect all categories:

const $ = db.command.aggregate
db
  .collection('passages')
  .aggregate()
  .group({
    _id: null,
    categories: $.addToSet('$category')
  })
  .end()

The returned result is as follows:

{ "_id": null, "categories": [ "System", "web" ] }

Array Fields

The type of the tags field value in each record is an array, and arrays are not automatically flattened:

const $ = db.command.aggregate
db
  .collection('passages')
  .aggregate()
  .group({
    _id: null,
    tagsList: $.addToSet('$tags')
  })
  .end()

The returned result is as follows:

{ "_id": null, "tagsList": [ [ "C++", "C" ], [ "JavaScript", "CSS" ] ] }