- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $unsetField (aggregation)
$unsetField (aggregation)¶
On this page
Definition¶
-
$unsetField¶ New in version 5.0.
Removes a specified field in a document.
You can use
$unsetFieldto remove fields with names that contain periods (.) or that start with dollar signs ($).$unsetFieldis an alias for$setFieldusing$$REMOVEto remove fields.
Syntax¶
$unsetField has the following syntax:
You must provide the following fields:
| Field | Type | Description |
|---|---|---|
field |
String | Field in the input object that you want to add, update, or
remove. field can be any valid expression that resolves to a string
constant. |
input |
Object | Document that contains the field that you want to add or
update. input must resolve to an object, missing,
null, or undefined. |
Behavior¶
- If
inputevaluates tomissing,undefined, ornull,$unsetFieldreturnsnulland does not updateinput. - If
inputevaluates to anything other than an object,missing,undefined, ornull,$unsetFieldreturns an error. - If
fieldresolves to anything other than a string constant,$unsetFieldreturns an error. - If
fielddoesn’t exist ininput,$unsetFieldadds it. $unsetFielddoesn’t implicitly traverse objects or arrays. For example,$unsetFieldevaluates afieldvalue of"a.b.c"as a top-level field"a.b.c"instead of as a nested field,{ "a": { "b": { "c": } } }.
Examples¶
Remove Fields that Contain Periods (.)¶
Consider the inventory collection:
Use the $replaceWith pipeline stage and the
$unsetField operator to remove the "price.usd" field
from each document:
The operation returns the following results:
Remove Fields that Start with a Dollar Sign ($)¶
Consider the inventory collection:
Use the $replaceWith pipeline stage with the
$unsetField and $literal operators to
remove the "$price" field from each document:
The operation returns the following results:
Remove A Subfield¶
Consider the inventory collection:
The "price" field contains a document with two subfields, "usd"
and "euro". You cannot use "price.euro" to identify and remove
"euro" because MongoDB parses "price.euro" as a top level field
name that happens to contain a period (.).
Use the $replaceWith pipeline stage with
$setField and a nested $unsetField
operation to remove the "euro" field:
The operation returns the following results:
See also