A filter document is a list of conditions joined by AND. Each key is a field path; each value is either a literal to match exactly or a document of operators, which always begin with $.
| Operator | Matches when the field... | Example |
|---|---|---|
| $eq | equals the value (the default) | { stock: { $eq: 0 } } |
| $ne | is not equal, or is absent | { stock: { $ne: 0 } } |
| $gt $gte | is greater than / or equal | { year: { $gte: 1980 } } |
| $lt $lte | is less than / or equal | { price: { $lt: 12 } } |
| $in | equals any value in the array | { tags: { $in: ['scifi', 'fantasy'] } } |
| $nin | equals none of them, or is absent | { 'author.country': { $nin: ['US'] } } |
{ stock: 0 } is shorthand for { stock: { $eq: 0 } }. Two operators inside one object act on the same field, so { $gte: 1980, $lte: 2013 } is a range; conditions on different fields sit side by side. $in takes candidate values, not a sub-query, and accepts regex literals among them, which $nin does not.
db.books.find({ year: { $gte: 1980, $lte: 2013 }, tags: { $ne: 'cyberpunk' } },
{ title: 1, year: 1, _id: 0 })
db.books.find({ price: { $lt: 12 } }, { title: 1, price: 1, _id: 0 })
db.books.find({}, { title: 1, price: 1, _id: 0 }).sort({ price: -1 }).limit(1)[ { title: 'Ancillary Justice', year: 2013 } ]
[ { title: 'Neuromancer', price: 9.5 } ]
[ { title: 'Snow Crash', price: '11.25' } ]The second argument is a projection (Projections), which keeps the printed output short; note what $ne: 'cyberpunk' did with an array field, keeping documents in which no element equals cyberpunk.
The last two queries are the type trap. MongoDB 1,815 compares values of the same BSON type and never converts across types; it orders by type instead. Snow Crash costs '11.25' — a string — so it escapes the numeric range, and the descending sort puts it ahead of every number. From lowest, BSON sorts MinKey, null, numbers, string, object, array, binData, ObjectId, boolean, date, timestamp, regex, MaxKey. Numeric types are the exception: an int 14, a double 14.0 and a Decimal128 "14.00" compare equal. Guard types at the write end with $jsonSchema (Regex and Evaluation) or a Mongoose 243,355 schema (Schemas).