In MongoDB, query filters allow you to retrieve specific documents from a collection based on certain conditions. These filters use operators to specify the criteria for matching documents. MongoDB’s query language is flexible and offers a wide variety of operators that enable complex queries for different use cases.
Here’s a detailed overview of query filters and the various operators you can use to filter and query your data.
A basic query in MongoDB involves specifying one or more field-value pairs to match documents. MongoDB matches documents where the field values meet the given criteria.
Find all documents in the users
collection where age
is 30
:
javascript
Copy code
db.users.find({ age: 30 });
This query will return all documents where the age
field is equal to 30
.
MongoDB provides a rich set of query operators to match documents based on more complex conditions. These operators can be grouped into categories such as comparison, logical, element, and evaluation operators.
These operators allow you to perform more advanced filtering based on the values in fields.
$eq
(Equal to): Matches documents where the field is equal to the specified value.Example (find users with age 30):javascriptCopy codedb.users.find({ age: { $eq: 30 } });
$ne
(Not equal to): Matches documents where the field is not equal to the specified value.Example (find users whose age is not 30):javascriptCopy codedb.users.find({ age: { $ne: 30 } });
$gt
(Greater than): Matches documents where the field value is greater than the specified value.Example (find users older than 25):javascriptCopy codedb.users.find({ age: { $gt: 25 } });
$gte
(Greater than or equal to): Matches documents where the field value is greater than or equal to the specified value.Example (find users aged 25 or older):javascriptCopy codedb.users.find({ age: { $gte: 25 } });
$lt
(Less than): Matches documents where the field value is less than the specified value.Example (find users younger than 30):javascriptCopy codedb.users.find({ age: { $lt: 30 } });
$lte
(Less than or equal to): Matches documents where the field value is less than or equal to the specified value.Example (find users aged 30 or younger):javascriptCopy codedb.users.find({ age: { $lte: 30 } });
$in
(In): Matches documents where the field’s value is in the specified array.Example (find users who are either 25 or 30 years old):javascriptCopy codedb.users.find({ age: { $in: [25, 30] } });
$nin
(Not in): Matches documents where the field’s value is not in the specified array.Example (find users who are neither 25 nor 30 years old):javascriptCopy codedb.users.find({ age: { $nin: [25, 30] } });
Logical operators allow combining multiple query conditions.
$and
: Matches documents that satisfy all the specified conditions. This operator is often implicit in queries where multiple conditions are combined.Example (find users who are older than 20 and younger than 30):javascriptCopy codedb.users.find({ $and: [{ age: { $gt: 20 } }, { age: { $lt: 30 } }] });
$or
: Matches documents that satisfy at least one of the specified conditions.Example (find users who are either 25 or 30 years old):javascriptCopy codedb.users.find({ $or: [{ age: 25 }, { age: 30 }] });
$not
: Matches documents where the field value does not match the specified condition.Example (find users who are not 30 years old):javascriptCopy codedb.users.find({ age: { $not: { $eq: 30 } } });
$nor
: Matches documents that do not satisfy any of the specified conditions (opposite of $or
).Example (find users who are neither 25 nor 30 years old):javascriptCopy codedb.users.find({ $nor: [{ age: 25 }, { age: 30 }] });
These operators check for the existence, type, or presence of values in fields.
$exists
: Matches documents where a field exists (or does not exist).Example (find users who have an email
field):javascriptCopy codedb.users.find({ email: { $exists: true } });
$type
: Matches documents where the field is of a specific BSON data type.Example (find documents where age
is an integer):javascriptCopy codedb.users.find({ age: { $type: "int" } });
These operators are used to query fields that contain arrays.
$all
: Matches documents where the field is an array that contains all the specified values.Example (find users who have both “developer” and “mongodb” tags):javascriptCopy codedb.users.find({ tags: { $all: ["developer", "mongodb"] } });
$elemMatch
: Matches documents where at least one element in the array satisfies the specified query.Example (find users who have a tag that is both “developer” and “mongodb”):javascriptCopy codedb.users.find({ tags: { $elemMatch: { $eq: "developer", $eq: "mongodb" } } });
$size
: Matches documents where the array has a specific number of elements.Example (find users who have exactly 3 tags):javascriptCopy codedb.users.find({ tags: { $size: 3 } });
You can use regular expressions to match strings in text fields.
$regex
: Matches documents where the field value matches a regular expression pattern.Example (find users whose name starts with “J”):javascriptCopy codedb.users.find({ name: { $regex: /^J/ } });
$options
: Specifies options for the regular expression, such as case-insensitivity.Example (find users whose name starts with “j” or “J”, case-insensitive):javascriptCopy codedb.users.find({ name: { $regex: "^j", $options: "i" } });
You can use multiple operators to perform range queries.
db.users.find({ age: { $gte: 20, $lte: 30 } });
db.users.find({ age: { $gt: 25, $lt: 40 } });
In addition to filtering documents, MongoDB allows you to specify which fields to include or exclude in the result. This is done using projection.
1
(include): Specifies that the field should be included in the result.0
(exclude): Specifies that the field should be excluded from the result.Example (find users but exclude the email
field):
javascript
Copy code
db.users.find({}, { email: 0 });
Example (find users and include only name
and age
):
javascript
Copy code
db.users.find({}, { name: 1, age: 1 });
You can sort the query results using the sort()
method.
1
(ascending order): Sorts the results in ascending order.-1
(descending order): Sorts the results in descending order.Example (sort users by age in ascending order):
javascript
Copy code
db.users.find().sort({ age: 1 });
Example (sort users by age in descending order):
javascript
Copy code
db.users.find().sort({ age: -1 });
MongoDB provides methods to limit and skip results.
limit()
: Limits the number of documents returned.Example (limit the result to 3 users):javascriptCopy codedb.users.find().limit(3);
skip()
: Skips the specified number of documents.Example (skip the first 2 users):javascriptCopy codedb.users.find().skip(2);
MongoDB provides a powerful query system that allows for filtering, sorting, and processing data using a wide range of query operators. Whether you’re using simple equality filters, performing range queries, or combining multiple conditions with logical operators, MongoDB’s flexible query language enables