Apply Multiple Conditions
In this step, you will learn to apply multiple conditions to filter documents in a MongoDB collection. This allows for more precise queries by combining several criteria.
First, open your terminal and start the MongoDB Shell. This interactive shell is where you will execute all your database commands.
mongosh
Once inside the mongosh shell, you will see a > prompt. Let's switch to a new database called school_database and create a students collection with some sample data.
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" }
]);
This command inserts four documents into the students collection. Now, let's find students who meet multiple conditions. We will use the $and operator to find students who are 20 years or older AND have a grade of "A".
db.students.find({
$and: [{ age: { $gte: 20 } }, { grade: "A" }]
});
This query uses $gte, which stands for "greater than or equal to", and $and to ensure both conditions are met. The output will show Alice and Charlie:
[
{
_id: ObjectId("..."),
name: 'Alice',
age: 22,
grade: 'A',
major: 'Computer Science'
},
{
_id: ObjectId("..."),
name: 'Charlie',
age: 25,
grade: 'A',
major: 'Physics'
}
]
Next, let's use the $or operator to find documents that match at least one of several conditions. This query finds students who are either majoring in "Computer Science" OR are younger than 21.
db.students.find({
$or: [{ major: "Computer Science" }, { age: { $lt: 21 } }]
});
This query uses $lt, which means "less than". The result will include Alice and David (Computer Science majors) and Bob and David (under 21). Since David matches both, he appears once.
[
{
_id: ObjectId("..."),
name: 'Alice',
age: 22,
grade: 'A',
major: 'Computer Science'
},
{
_id: ObjectId("..."),
name: 'Bob',
age: 20,
grade: 'B',
major: 'Mathematics'
},
{
_id: ObjectId("..."),
name: 'David',
age: 19,
grade: 'C',
major: 'Computer Science'
}
]
In the next step, you will explore more comparison operators. For now, you can remain in the mongosh shell.