$unset
The $unset stage in the aggregation pipeline is used to remove specified fields from documents. This can be particularly useful when you need to exclude certain fields from the results of an aggregation query for reasons such as privacy, reducing payload size, or simply cleaning up the output.
Syntax
{
$unset: "<field1>" | ["<field1>", "<field2>", ...]
}
Parameters
field
stringrequiredThe names of the fields to remove from the documents. Can be a single field name or an array of field names.
Examples
Sample Data
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop",
"location": { "lat": -89.2384, "lon": -46.4012 },
"sales": { "totalSales": 75670 }
}
Remove a single field
Remove the location field from documents.
This query excludes the location field from results.
Query:
db.stores.aggregate([
{ $unset: "store.location" }
])
Output:
[
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"store": {
"name": "Downtown Store",
"sales": { "totalSales": 15000 }
}
}
]
Remove multiple fields
Remove the location and sales.totalSales fields.
This query excludes multiple fields from results.
Query:
db.stores.aggregate([
{ $unset: ["store.location", "store.sales.totalSales"] }
])
Output:
[
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"store": {
"name": "Downtown Store",
"sales": {
"salesByCategory": [
{ "category": "Electronics", "totalSales": 5000 }
]
}
}
}
]