$setDifference

Returns an array containing elements that exist in the first set but not in the second set, performing set subtraction operation.

Syntax

{ $setDifference: [<array_expression1>, <array_expression2>] }

Parameters

array_expression1objectrequired

The first array expression (elements to keep)

array_expression2objectrequired

The second array expression (elements to subtract)

Examples

Find unique elements

Get elements that exist in first array but not in second

Query:

db.products.aggregate([{ $project: { uniqueTags: { $setDifference: ["$allTags", "$commonTags"] } } }])

Output:

Documents with uniqueTags containing tags not found in commonTags array

Exclude specific values

Remove specific values from an array using set difference

Query:

db.inventory.aggregate([{ $project: { filteredItems: { $setDifference: ["$items", ["discontinued", "obsolete"]] } } }])

Output:

Documents with filteredItems array excluding discontinued and obsolete items

Compare user permissions

Find permissions that exist in required but not in current

Query:

db.users.aggregate([{ $project: { missingPermissions: { $setDifference: ["$requiredPermissions", "$currentPermissions"] } } }])

Output:

Documents with missingPermissions array showing what permissions user lacks

Related