$exists

Matches documents where the specified field exists, regardless of its value.

Syntax

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

Parameters

fieldstringrequired

The field name to check for existence

booleanstringrequired

true to match documents where field exists, false to match documents where field does not exist

Examples

Find documents where price field exists

Find all products that have a price field defined

Query:

db.products.find({ "price": { $exists: true } })

Output:

Documents where the price field is present, regardless of its value

Find documents without description field

Find products that don't have a description field

Query:

db.products.find({ "description": { $exists: false } })

Output:

Documents where the description field is not present

Check nested field existence

Check if a nested field within an object exists

Query:

db.stores.find({ "location.coordinates": { $exists: true } })

Output:

Documents where the coordinates field exists within the location object

Find documents with array field

Match documents where an array field exists

Query:

db.stores.find({ "tags": { $exists: true } })

Output:

Documents that have a tags array field, even if it's empty

Combine with other operators

Use $exists with other query operators

Query:

db.products.find({ "price": { $exists: true, $gt: 50 } })

Output:

Documents where price field exists and is greater than 50

Related