$unset

Definition

  • $unset
  • The $unset operator deletes a particular field. Considerthe following syntax:
  1. { $unset: { <field1>: "", ... } }

The specified value in the $unset expression (i.e. "")does not impact the operation.

To specify a <field> in an embedded document or in an array, usedot notation.

Behavior

If the field does not exist, then $unset does nothing (i.e.no operation).

When used with $ to match an array element, $unsetreplaces the matching element with null rather than removing thematching element from the array. This behavior keeps consistent thearray size and element positions.

Example

The following update() operation uses the$unset operator to remove the fields quantity andinstock from the first document in the products collectionwhere the field sku has a value of unknown.

  1. db.products.update(
  2. { sku: "unknown" },
  3. { $unset: { quantity: "", instock: "" } }
  4. )

See also

db.collection.update(),db.collection.findAndModify()