Read Documents: Part 2
Learn and practice the find and findOne commands to read documents, and use the operators, $gt, $gte, $lt, $lte, $ne, and $nin, in the filter query.
$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.
Press + to interact
db.tasks.insertMany([{name: 'Task 1',priority: 1,},{name: 'Task 2',priority: 2,}]);
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
}
]
... ...
Access this course and 1400+ top-rated courses and projects.