Apply Multiple Conditions
In this step, you'll learn how to apply multiple conditions when querying MongoDB collections. Multiple conditions allow you to create more precise and complex queries to filter your data effectively.
First, open a terminal and launch the MongoDB shell:
mongosh
Now, let's create a sample collection of students to demonstrate multiple condition queries:
use school_database
db.students.insertMany([
{ name: "Alice", age: 22, grade: "A", major: "Computer Science" },
{ name: "Bob", age: 20, grade: "B", major: "Mathematics" },
{ name: "Charlie", age: 25, grade: "A", major: "Physics" },
{ name: "David", age: 19, grade: "C", major: "Computer Science" }
])
Let's explore how to apply multiple conditions using the $and
operator. This allows us to specify multiple conditions that must all be true:
db.students.find({
$and: [{ age: { $gte: 20 } }, { grade: "A" }]
});
This query will return students who are 20 years or older AND have an "A" grade. Let's break down the conditions:
$gte
means "greater than or equal to"
$and
ensures both conditions must be met
You should see output similar to:
[
{
_id: ObjectId("..."),
name: 'Alice',
age: 22,
grade: 'A',
major: 'Computer Science'
},
{
_id: ObjectId("..."),
name: 'Charlie',
age: 25,
grade: 'A',
major: 'Physics'
}
]
We can also use the $or
operator to find documents that match at least one condition:
db.students.find({
$or: [{ major: "Computer Science" }, { age: { $lt: 21 } }]
});
This query will return students who are either in Computer Science OR under 21 years old.
The result will include students like David (under 21) and Alice and David (Computer Science majors).