$unset

Removes specified fields from documents, effectively deleting the field and its value entirely.

Syntax

{ $unset: { <field1>: "", <field2>: "", ... } }

Parameters

fieldstringrequired

Field name to remove from document

Examples

Remove sensitive information

Delete fields containing sensitive data from user documents

Query:

db.users.updateOne({ userId: "user123" }, { $unset: { ssn: "", creditCard: "" } })

Output:

Removes ssn and creditCard fields completely from the user document

Clean up temporary fields

Remove temporary or deprecated fields from documents

Query:

db.products.updateMany({}, { $unset: { tempField: "", oldDescription: "", deprecated: "" } })

Output:

Removes specified temporary fields from all product documents

Related