$exists

Definition

  • $exists
  • Syntax: { field: { $exists: <boolean> } }

When <boolean> is true, $exists matches the documents thatcontain the field, including documents where the field value isnull. If <boolean> is false, the query returns only thedocuments that do not contain the field. [1]

MongoDB $exists does not correspond to SQL operatorexists. For SQL exists, refer to the $inoperator.

See also

$nin, $in, andQuery for Null or Missing Fields.

[1]Starting in MongoDB 4.2, users can no longer use the query filter$type: 0 as a synonym for$exists:false. To query for null or missing fields, seeQuery for Null or Missing Fields.

Examples

Exists and Not Equal To

Consider the following example:

  1. db.inventory.find( { qty: { $exists: true, $nin: [ 5, 15 ] } } )

This query will select all documents in the inventory collectionwhere the qty field exists and its value does not equal 5 or15.

Null Values

The following examples uses a collection named records with thefollowing documents:

  1. { a: 5, b: 5, c: null }
  2. { a: 3, b: null, c: 8 }
  3. { a: null, b: 3, c: 9 }
  4. { a: 1, b: 2, c: 3 }
  5. { a: 2, c: 5 }
  6. { a: 3, b: 2 }
  7. { a: 4 }
  8. { b: 2, c: 4 }
  9. { b: 2 }
  10. { c: 6 }

$exists: true

The following query specifies the query predicate a: { $exists: true }:

  1. db.records.find( { a: { $exists: true } } )

The results consist of those documents that contain the field a,including the document whose field a contains a null value:

  1. { a: 5, b: 5, c: null }
  2. { a: 3, b: null, c: 8 }
  3. { a: null, b: 3, c: 9 }
  4. { a: 1, b: 2, c: 3 }
  5. { a: 2, c: 5 }
  6. { a: 3, b: 2 }
  7. { a: 4 }

$exists: false

The following query specifies the query predicate b: { $exists: false }:

  1. db.records.find( { b: { $exists: false } } )

The results consist of those documents that do not contain the fieldb:

  1. { a: 2, c: 5 }
  2. { a: 4 }
  3. { c: 6 }

Starting in MongoDB 4.2, users can no longer use the query filter$type: 0 as a synonym for$exists:false. To query for null or missing fields, seeQuery for Null or Missing Fields.

See also

Query for Null or Missing Fields