Query Filters and Comparison Operators
MongoDB query filters determine which documents are selected by a read, update, or delete operation.
A filter is a document describing conditions that documents must satisfy.
Equality
db.products.find({ category: "electronics" });
This matches documents where the category field equals the specified value.
Comparison operators
MongoDB provides comparison operators such as:
$eq: equal to.$ne: not equal to.$gt: greater than.$gte: greater than or equal to.$lt: less than.$lte: less than or equal to.$in: matches any specified value.$nin: matches none of the specified values.
Greater than and less than
db.products.find({ price: { $gt: 1000 } });
This selects products with a numeric price greater than 1000, subject to MongoDB's comparison semantics and the stored field types.
Range query
db.products.find({
price: {
$gte: 500,
$lte: 2000
}
});
The query requires the price to be at least 500 and at most 2000.
$in
db.products.find({
category: { $in: ["electronics", "books"] }
});
The query matches either category. $in is also useful for matching array fields against any of the supplied values.
$nin
db.products.find({
category: { $nin: ["electronics", "books"] }
});
$nin matches documents where the field value is not in the supplied list. It can also match documents where the field is missing, so consider whether that behavior is appropriate for your requirement.
$ne
db.products.find({ price: { $ne: 1000 } });
$ne is not equivalent to checking that a field exists and has a different value. Depending on the query, documents with missing fields can match $ne filters.
Type awareness
If a price field contains the string "1500", do not assume that it behaves like the number 1500 in a numeric range filter. Use consistent types and inspect legacy data when query results seem unexpected.
Query selectivity
A filter that matches a small fraction of a collection may be more selective than one that matches nearly every document. Indexes and data distribution affect query performance, which will be covered in the indexing chapters.
EqualNot equalGreater thanLess thanMembershipdb.filterDemo.insertMany([
{ name: "Keyboard", price: 1500, category: "electronics" },
{ name: "Book", price: 500, category: "books" },
{ name: "Monitor", price: 8000, category: "electronics" },
{ name: "Chair", price: 2500, category: "furniture" }
]);
// Price greater than 1000.
db.filterDemo.find({ price: { $gt: 1000 } });
// Inclusive price range.
db.filterDemo.find({
price: { $gte: 500, $lte: 2500 }
});
// Match one of several categories.
db.filterDemo.find({
category: { $in: ["electronics", "books"] }
});- Query filters define which documents an operation affects.
- Comparison operators support equality, inequalities, and membership tests.
- $in matches any specified value.
- $ne and $nin may match documents where a field is missing.
- Consistent BSON types are important for predictable filtering.
What does `{ price: { $gte: 500, $lte: 2000 } }` mean?