AggregateCommand.setDifference(value: Expression[]): Object

View Markdown

Last edited on 2026-07-04

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

An aggregation operator that takes two collections as input and outputs elements that exist only in the first collection.

Parameters

value: Expression[]

[<expression1>, <expression2>]

Return Value

Object

API Description

Usage format is as follows:

setDifference([<expression1>, <expression2>])

Example Code

Suppose the collection test contains the following data:

{ "_id": 1, "A": [ 1, 2 ], "B": [ 1, 2 ] }
{ "_id": 2, "A": [ 1, 2 ], "B": [ 2, 1, 2 ] }
{ "_id": 3, "A": [ 1, 2 ], "B": [ 1, 2, 3 ] }
{ "_id": 4, "A": [ 1, 2 ], "B": [ 3, 1 ] }
{ "_id": 5, "A": [ 1, 2 ], "B": [ ] }
{ "_id": 6, "A": [ 1, 2 ], "B": [ {}, [] ] }
{ "_id": 7, "A": [ ], "B": [ ] }
{ "_id": 8, "A": [ ], "B": [ 1 ] }

The code below uses setDifference to find numbers that exist only in B:

db.collection('test')
  .aggregate()
  .project({
    isBOnly: $.setDifference(['$B', '$A'])
  })
  .end()
{ "_id": 1, "isBOnly": [] }
{ "_id": 2, "isBOnly": [] }
{ "_id": 3, "isBOnly": [3] }
{ "_id": 4, "isBOnly": [3] }
{ "_id": 5, "isBOnly": [] }
{ "_id": 6, "isBOnly": [{}, []] }
{ "_id": 7, "isBOnly": [] }
{ "_id": 8, "isBOnly": [1] }