$unset (aggregation)

Definition

  • $unset

New in version 4.2.

Removes/excludes fields from documents.

Syntax

The $unset stage has the following syntax:

  • To remove a single field, the $unset takes a string thatspecifies the field to remove:
  1. { $unset: "<field>" }
  • To remove multiple fields, the $unset takes an array offields to remove.
  1. { $unset: [ "<field1>", "<field2>", ... ] }

Considerations

$unset and $project

The $unset is an alias for the $projectstage that removes/excludes fields:

  1. { $project: { "<field1>": 0, "<field2>": 0, ... } }

Embedded Fields

To remove/exclude a field or fields within an embedded document, youcan use the dot notation, as in:

  1. { $unset: "<field.nestedfield>" }

or

  1. { $unset: [ "<field1.nestedfield>", ...] }

Examples

Create a sample books collection with the following documents:

  1. db.books.insertMany([
  2. { "_id" : 1, title: "Antelope Antics", isbn: "0001122223334", author: { last:"An", first: "Auntie" }, copies: [ { warehouse: "A", qty: 5 }, { warehouse: "B", qty: 15 } ] },
  3. { "_id" : 2, title: "Bees Babble", isbn: "999999999333", author: { last:"Bumble", first: "Bee" }, copies: [ { warehouse: "A", qty: 2 }, { warehouse: "B", qty: 5 } ] }
  4. ])

Remove a Single Field

The following example removes the top-level field copies:

  1. db.books.aggregate([ { $unset: "copies" } ])

Alternatively, you can also use the following syntax:

  1. db.books.aggregate([ { $unset: [ "copies" ] } ])

Either operation returns the following documents:

  1. { "_id" : 1, "title" : "Antelope Antics", "isbn" : "0001122223334", "author" : { "last" : "An", "first" : "Auntie" } }
  2. { "_id" : 2, "title" : "Bees Babble", "isbn" : "999999999333", "author" : { "last" : "Bumble", "first" : "Bee" } }

Remove Top-Level Fields

The following example removes the top-level fields isbn andcopies:

  1. db.books.aggregate([
  2. { $unset: [ "isbn", "copies" ] }
  3. ])

The $unset operation outputs the following documents:

  1. { "_id" : 1, "title" : "Antelope Antics", "author" : { "last" : "An", "first" : "Auntie" } }
  2. { "_id" : 2, "title" : "Bees Babble", "author" : { "last" : "Bumble", "first" : "Bee" } }

Remove Embedded Fields

The following example removes the top-level field isbn, theembedded field first (from the name document) and the embedded fieldwarehouse (from the elements in the copies array):

  1. db.books.aggregate([
  2. { $unset: [ "isbn", "author.first", "copies.warehouse" ] }
  3. ])

The $unset operation outputs the following documents:

  1. { "_id" : 1, "title" : "Antelope Antics", "author" : { "last" : "An" }, "copies" : [ { "qty" : 5 }, { "qty" : 15 } ] }
  2. { "_id" : 2, "title" : "Bees Babble", "author" : { "last" : "Bumble" }, "copies" : [ { "qty" : 2 }, { "qty" : 5 } ] }