OPTIONS

$exists

On this page

Definition

$exists

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

When <boolean> is true, $exists matches the documents that contain the field, including documents where the field value is null. If <boolean> is false, the query returns only the documents that do not contain the field.

MongoDB $exists does not correspond to SQL operator exists. For SQL exists, refer to the $in operator.

Examples

Exists and Not Equal To

Consider the following example:

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

This query will select all documents in the inventory collection where the qty field exists and its value does not equal 5 or 15.

Null Values

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

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

$exists: true

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

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:

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

$exists: false

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

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

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

{ a: 2, c: 5 }
{ a: 4 }
{ c: 6 }

Was this page helpful?

Yes No

Thank you for your feedback!

We're sorry! You can Report a Problem to help us improve this page.