Read Documents: Part 2
Explore how to use MongoDB comparison and logical query operators to filter documents effectively. Learn to apply operators such as $gt, $gte, $lt, $lte, $in, $ne, and $nin to fetch, exclude, or match documents based on field values. This lesson helps you build precise queries for reading data in MongoDB collections.
$gt: Greater than (>)
The $gt operator is used to match documents that have a field value greater than provided value.
Let’s insert some tasks with a numeric field value.
Next, we build a query to fetch tasks that have a greater priority than 1.
db.tasks.find({
priority: {
$gt: 1,
},
});
This query returns the below output.
[
{
_id: ObjectId("60f98f8dac3c9ea06c0506aa"),
name: 'Task 2',
priority: 2
}
]
It doesn’t return the task with the priority: 1.
This operator works for string values as well, but it is not recommended. Below is a query example of how we use the $gt operator on the string field.
db.tasks.find({
name: {
$gt: 'Task 1',
},
});
This query returns the below output.
[
{
_id: ObjectId("60f98f8dac3c9ea06c0506aa"),
name: 'Task 2',
priority: 2
}
]
... ...