0PricingLogin
MongoDB Academy · Lesson

Element Operators and Type Checks

Learners will query for the presence or type of a field using $exists and $type to handle optional or mixed-type data.

Optional Fields in Flexible Schemas

MongoDB's flexible schema means some documents in a collection may have fields that others lack. A user document might have an optional phoneNumber field—some users provided it, others did not. In SQL, you would handle this with a NULL value in every row. In MongoDB, the field simply does not exist in some documents.

This difference has important implications for querying. MongoDB's element operators—primarily $exists and $type—let you query based on the presence or type of a field, rather than its value.

$exists: Checking Field Presence

$exists: true matches documents that have the specified field (regardless of its value, even if the value is null). $exists: false matches documents where the field is completely absent.

This distinction is subtle but important: a document with { phone: null } does match { phone: { $exists: true } } because the field exists—it is just null. Only a document with no phone field at all matches { phone: { $exists: false } }.

// Find users who have provided a phone number (field exists)
db.users.find({ phone: { $exists: true } });

// Find users who never provided a phone number (field absent)
db.users.find({ phone: { $exists: false } });

// Key distinction:
// { phone: null }    => $exists: true (field exists, value is null)
// { name: 'Alice' }  => $exists: false (no phone field at all)

// Combined: field exists AND is not null
db.users.find({ phone: { $exists: true, $ne: null } });

All lessons in this course

  1. Comparison Operators: $eq, $gt, $lt, $in
  2. Logical Operators: $and, $or, $nor, $not
  3. Element Operators and Type Checks
  4. Regex Queries and Pattern Matching
← Back to MongoDB Academy