MongoDB Less Than or Equal To
“In MongoDB, we can use the built-in comparison operators to perform various comparison operations. We can use these operators to compare values in a given document or a native value.
This post will focus on the less than or equal to operator. This operator allows us to select documents where the values in a given field are less than or equal to a given value.”
Let us explore.
The following shows the operator syntax and how to use it.
The query should return the results where the values of a given field are less than or equal to the value specified in the operator.
Let us explore some basic examples.
Consider the example collection and documents provided in the query below:
Once we have the target documents, we can proceed and use the $lte operator.
Fetch Documents Matching a Specific Condition
We can use the less than or equal to operator to fetch documents matching a specific condition.
For example, we can fetch documents whose price is less than or equal to 600. The query is as shown:
This should filter and return the requested documents as shown:
Updating Documents Matching a Specific Condition
We can also use the less than or equal to operator to update documents matching a specific condition.
For example, suppose we wish to increase the number of products priced at 400 and below.
We can run the query as shown below:
The query should fetch all the documents with a price value less than or equal to 400. It will then pass that to the set operator and update the quantity to 1600.
We can then query the collection to view the changes as:
You can use the updateOne() method to update a single document matching the specified document.
In this post, we explored how to use MongoDB less than or equal to operators to fetch documents matching a given set of conditions. We hope you enjoyed this tutorial. Check out our other MongoDB tutorials to learn more.