Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 70 ยท Query operators

Element and Evaluation Operators

Test whether a field exists or has a given BSON type, match text with $regex, compare two fields with $expr, use $mod, and see $jsonSchema in queries.

Comparison operators ask "what is the value?". Two other families ask different questions. Element operators ($exists, $type) look at the shape of a document: is the field there, and what type is it? Evaluation operators ($regex, $expr, $mod, $jsonSchema) run a small computation on the value, such as a pattern match, an arithmetic test or a schema check.

Because MongoDB collections have no fixed columns, these operators matter more than they do in a relational database. Two documents in the same collection can differ: one has an email, one has email: null, one has no email key at all, and one stores the age as the text "29". This lesson shows how to find each of those cases. The mongosh snippets in plain code blocks are real MongoDB syntax and cannot run here; every TryIt uses the site's practice engine, a small JavaScript matcher that follows MongoDB's rules for these operators. The engine is a stand-in with no indexes and no BSON, so it guesses int versus double from the JavaScript number, which a real driver may decide differently.

Element operators

$exists Is the field present in the document?
$type Which BSON type does the value have?

They inspect the shape of the data, not its meaning.

1 / 2

$exists and the null-versus-missing puzzle

{ field: { $exists: true } } matches documents that contain the key, whatever its value, including null. { field: { $exists: false } } matches documents where the key is absent. That sounds simple until you meet null, because a plain equality test against null is generous:

JavaScript
db.users.find({ email: null })

This matches documents where email is null and documents where email does not exist. It is the single most common surprise in MongoDB filters. If you need to tell the cases apart, combine the operators:

You want Filter
Key missing { email: { $exists: false } }
Key present with value null { email: { $type: "null" } }
Null or missing { email: null }
Has a real value { email: { $ne: null } }

$ne: null matches only documents where the key exists and is not null, so it is the idiomatic "has a value" test. An empty string is still a value, so "" passes it. Run the next example to see all four filters side by side.

JS Null, missing and empty

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the first two lines: email: null returns Ben (null) and Cleo (missing), while $exists: false returns only Cleo. The last filter, $nin: [null, ""], is a handy way to say "a usable email", because $nin with null also excludes missing fields. Use $exists when you need to distinguish missing from null; otherwise null equality is usually what you want.

$type: finding values of the wrong type

Every BSON value has a type, and a field can hold different types in different documents, usually because of a bug: an import that stored numbers as strings, or an app version that wrote dates as text. $type finds them. It accepts a type name or an array of names ({ $type: ["string", "null"] }), and the alias "number" covers every numeric type (int, long, double and decimal). Other common names are "string", "bool", "date", "objectId", "array" and "object". BSON Types lists them all.

Two behaviors to remember. $type: "array" matches the field when it is an array itself, but any other type name tested against an array field matches if some element has that type. And comparison operators bracket by type, so { age: { $gt: 30 } } never matches the text "31". A bad type usually means a missing result, not an error.

JS Hunting values of the wrong type

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Ben's age "29" is skipped by $gt: 28, found by $type: "string" and caught by the "not a number" filter. Note the last line: Dev's tags is a bare string, and Cleo's has string elements, so both match $type: "string". In real MongoDB, a document with age: 31 could be an int or a double, depending on how it was written; the stand-in treats whole numbers as int and others as double.

$regex: pattern matching

$regex matches string fields against a regular expression (PCRE syntax in MongoDB, so a little different from JavaScript in the corners). You can write it as an operator with optional $options, or as a regex literal:

JavaScript
db.users.find({ email: { $regex: "@example\\.com$", $options: "i" } })
db.users.find({ email: /@example\.com$/i })

The common options are i (ignore case), m (anchors match at line breaks) and s (dot matches newlines). Remember to escape the dot in JSON-style strings with a double backslash. Regular expressions have their own performance rules, which are the subject of Text Matching and Regular Expressions.

$mod and $expr

$mod: [divisor, remainder] matches numbers whose remainder after division equals the remainder you give. It is handy for even/odd splits or sampling by id, and it skips non-numeric values.

$expr is the odd one out. Ordinary filters compare a field with a constant. $expr lets you use aggregation expressions inside find, so you can compare two fields of the same document or do arithmetic first:

JavaScript
// stock at or below the reorder level
db.products.find({ $expr: { $lte: ["$stock", "$reorderLevel"] } })

Inside $expr, field names are written as "$stock" strings, and operators take arrays of arguments. You will meet the full expression language in Expressions and Operators. Two cautions: $expr generally cannot use indexes as effectively as a plain comparison, and unlike plain filters it does not do type bracketing the same way, so check mixed-type data first.

JS $regex, $mod and $expr together

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Ben's upper-case email only matches with the i option, and his text age "29" is ignored by $mod. The two $expr lines would be impossible with plain comparison operators, since the right-hand side is another field or a computed value.

$jsonSchema in a query

$jsonSchema matches documents that satisfy a JSON Schema document (MongoDB's dialect, with bsonType in place of type). It is mostly used for validation when you create a collection, covered in Schema Validation, but it also works as a filter. A very practical trick is to find the documents that violate your rules by wrapping the schema in $nor. This is a real mongosh snippet and cannot run here:

JavaScript
const schema = {
  bsonType: "object",
  required: ["name", "email"],
  properties: {
    email: { bsonType: "string", pattern: "@" },
    age: { bsonType: "int", minimum: 0 }
  }
};

db.users.find({ $jsonSchema: schema })            // valid documents
db.users.find({ $nor: [{ $jsonSchema: schema }] }) // invalid documents

Running the second query before you turn on validation tells you how much old data would fail the new rules.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which documents does { email: null } match?

    Equality with null matches both a stored null and a missing key. Use $exists or $type: 'null' to tell them apart.
  2. 2. How do you find documents where the key exists and is not null?

    $ne: null excludes both null and missing fields. $exists: true would still include fields that hold null, and $not cannot take a plain value.
  3. 3. What is $expr used for in a find filter?

    $expr evaluates an aggregation expression such as { $lte: ['$stock', '$reorderLevel'] } per document. It is not server-side JavaScript (that is $where).
  4. 4. A numeric field was imported as the string '29' for some documents. What does { age: { $gt: 28 } } do with them?

    Range comparisons bracket by type, so a string is never greater than a number. Use $type: 'string' to find the bad documents and fix them.

Summary

  • $exists tests whether a key is present; $type tests the BSON type (names or an array of names, plus the "number" alias).
  • { field: null } matches both null and missing. $ne: null means "present and not null". $type: "null" means "present and null".
  • $regex takes a pattern and $options (i, m, s), or you can use a regex literal; see the text lesson for performance.
  • $mod: [divisor, remainder] filters numbers by remainder.
  • $expr brings aggregation expressions into find, so fields of one document can be compared with each other.
  • $jsonSchema works as a filter too; wrap it in $nor to list documents that break your schema.

Next, filter documents by their array contents in Array Query Operators.