MongoDB Greater Than ($gt) Operator

MongoDB Greater Than ($gt) Operator

In this article, we will discuss MongoDB Greater Than ($gt) Operator with Examples. In MongoDB, data is stored in the BSON document. Here BSON is known as the binary document or binary representation of 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 Greater Than ($gt) Operator

MongoDB $gt operator is known as greater than. This operator selects only those documents whose field value is greater than the specified value. This operator generally works on BSON data types.

Syntax: {$gt: value}

Now we will learn how to use the $gt operator with the help of the following examples. So in this article to understand the MongoDB Greater Than ($gt) Operator, we are going to use the following database:

MongoDB Greater Than ($gt) 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 greater than 40 we use the find() function along with the $gt operator.

db.embeddedColl.find({Count:{$gt:40}}).pretty()

Output:

Example- Matching document fields

Example-Update Document Field

To update a document in the embeddedColl collection whose Count is greater than 40 with year = 2022. So we use updateOne() function along with the $gt operator.

db.embeddedColl.updateOne({Count:{$gt:40}}, {$set:{year: 2022}})

Here, {Count:{$gt:40}} is a filter document, and {$set:{year: 2022}} is updating the value of the field with the new one. Here updateOne() function updates one document at a time.

Output:

Image

Example- Update Embedded Document Field

To update the field of embedded documents in the embeddedColl collection whose Count is greater than 45 with year = 2022. So we use the updateMany() function along with the $gt operator.

db.embeddedColl.updateMany({“Articles.Count”:{$gt:45}}, {$set:{year: 2022}})

Output:

Example- Update Embedded Document Field

The updateMany() function updates multiple documents at a time. So in the above example, the updateMany() function updates two documents with year:2022 because they satisfy the filter document that is {“Articles.Count”:{$gt:45}}.

In the next article, I am going to discuss MongoDB Less Than ($lt) Operator with Examples. Here, in this article, I try to explain MongoDB Greater Than ($gt) Operator with Examples. I hope you enjoy this MongoDB Greater Than ($gt) Operator with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *