Query operators
Equality filters like { category: 'Kitchen' } only go so far. Query operators, which all start with $, let you ask for ranges, lists, missing fields, patterns and conditions on arrays.
Comparison
| Operator | Meaning |
|---|---|
$eq / $ne |
equal / not equal |
$gt / $gte |
greater than / or equal |
$lt / $lte |
less than / or equal |
$in / $nin |
in a list / not in a list |
Several operators on one field combine with AND: { price: { $gte: 40, $lte: 100 } } means 40 ≤ price ≤ 100.
Dates compare like numbers:
Logical operators
Fields at the top level are already ANDed. Use $or when any condition may match:
| Operator | Meaning |
|---|---|
$and |
All conditions (needed only when the same field appears twice, or to combine several $ors) |
$or |
At least one condition |
$nor |
None of the conditions |
$not |
Inverts an operator: { price: { $not: { $gt: 50 } } } |
Field existence and type
Documents can differ, so you often ask "does this field exist?":
Watch out for null: { field: null } matches documents where the field is null or missing:
$type checks the BSON type, which is handy for finding messy data such as prices stored as strings: { price: { $type: 'string' } }.
Regular expressions
A regex anchored at the start (/^abc/, case-sensitive) can use an index. Others scan every document, so for real search use Atlas Search or a text index.
Querying arrays
| Query | Matches when… |
|---|---|
{ tags: 'work' } |
any element equals 'work' |
{ tags: { $all: ['work', 'computer'] } } |
the array contains all of these |
{ tags: { $size: 2 } } |
the array has exactly 2 elements |
{ tags: ['work', 'gift'] } |
the array is exactly this, in this order |
{ 'tags.0': 'work' } |
the first element is 'work' |
Arrays of objects and $elemMatch
Orders contain an items array of objects. Dot notation reaches into each element:
But be careful when you combine two conditions on array elements. This query asks for orders with an item of qty >= 5 and an item priced over 5, and they can be different items:
The Notebook order matched because one item has qty 10 (a $3.50 notebook) and another item costs $6.75. To require one single element to match all conditions, use $elemMatch:
Expressions: comparing two fields
$expr lets you use aggregation expressions in a query, for example to compare two fields of the same document:
'$stock' with a dollar sign means "the value of the stock field".
Practice
- Find products that cost less than 10 or have the tag
'audio'. - Find customers aged 25 to 35 (inclusive) who are not in India.
- Find orders containing at least one item with
qtyof 4 or more, using$elemMatch. - Find customers whose email doesn't end in
example.com. (Expect none!)
1.Which filter finds products priced from 10 to 50 inclusive?
2.What does { nickname: null } match?
3.You need orders where a single item has both qty ≥ 5 and price > 5. What do you use?