Back to: MongoDB Tutorials
MongoDB Less Than ($lt) Operator with Examples
In this article, we will discuss MongoDB Less Than ($lt) Operator with Examples. Please read our previous article where we discussed MongoDB Greater Than ($gt) Operator with Examples. In MongoDB, the data is stored in the BSON document. Here BSON is known as the binary document or binary representation of the JSON document. BSON supports various types of values like strings, integers, etc. So to compare these values MongoDB provides comparison operators. Comparison operators return the values according to the value comparisons. MongoDB supports various comparison operators like $eq, $gt, $gte, $in, $lt, $lte, $ne, and $nin.
MongoDB Less Than ($lt) Operator
MongoDB $lt operator is known as less than. This operator selects only those documents whose field value is less than the specified value. This operator generally works on BSON data types.
Syntax: {$lt: value}
Now we will learn how to use the $lt operator with the help of the following examples. So in this article, we are going to use the following database to understand the MongoDB Less Than ($lt) Operator:
Here the collection name is embeddedColl and it contains 6 documents.
Example- Matching Document Fields
To select all the documents in the embeddedColl collection whose count is less than 50 we use the find() function along with the $lt operator.
db.embeddedColl.find({Count:{$lt:50}}).pretty()
Output:
Example-Update Document Field
To update a document in the embeddedColl collection whose Count is less than 50 with year = 2000. So we use updateOne() function along with the $lt operator.
db.embeddedColl.updateOne({Count:{$lt:50}}, {$set:{year: 2000}})
Here, {Count:{$lt:50}} is a filter document, and {$set:{year: 2000}} is updating the value of the field with the new one. Here, the updateOne() function updates one document at a time.
Output:
Example- Update Embedded Document Field
To update the field of embedded documents in the embeddedColl collection whose Count is less than 60 with year = 2011. So we use the updateMany() function along with the $lt operator.
db.embeddedColl.updateMany({“Articles.Count”:{$lt:60}}, {$set:{year: 2011}})
Output:
The updateMany() function updates multiple documents at a time. So in the above example, the updateMany() function updates two documents with year:2011 because they satisfy the filter document that is {“Articles.Count”:{$lt:60}}.
Here, in this article, I try to explain MongoDB Less Than ($lt) Operator with Examples. I hope you enjoy this article.