Skip to main content

db.command.aggregate.addToSet

1. Operator Description

Function: Adds a value to an array. If the value already exists in the array, no operation is performed. It can only be used in the group stage.

Declaration: db.command.aggregate.addToSet(expression)

2. Operator Parameters

FieldTypeRequiredDescription
-ExpressionRequiredA string expression is in the form of $ + specified field. If the value of the specified field is an array, the entire array will be treated as a single element.

3. Sample Code

Suppose the collection passages contains the following records:

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

Non-Array Field

The category field in each record contains non-array values. We use addToSet to collect all categories:

// Sample code in the Cloud Function environment
const tcb = require('@cloudbase/node-sdk')
const app = tcb.init({
env: 'xxx'
})

const db = app.database()
const $ = db.command.aggregate

exports.main = async (event, context) => {
const res = await db
.collection('passages')
.aggregate()
.group({
_id: null,
categories: $.addToSet('$category')
})
.end()
console.log(res.data)
}

The returned result is as follows:

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

Array Field

The tags field in each record contains array values, and the array will not be automatically expanded:

// Sample code in the Cloud Function environment
const tcb = require('@cloudbase/node-sdk')
const app = tcb.init({
env: 'xxx'
})

const db = app.database()
const $ = db.command.aggregate

exports.main = async (event, context) => {
const res = await db
.collection('passages')
.aggregate()
.group({
_id: null,
tagsList: $.addToSet('$tags')
})
.end()
console.log(res.data)
}

The returned result is as follows:

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