What is $gt in MongoDB?

Overview

$gt means “greater than.” It is a query operator and one of the comparison operators in MongoDB. It selects or matches documents with a path or field value greater than the specified value.

Syntax

{field: {$gt: value}}

Parameters

field: This is a valid document path.

value: This is the specified value that will be used to match documents with field values greater than it.

Return value

This operator returns documents that match the specified value.

Example

Let’s take a collection called fruits. Let’s display the documents it contains:

db.fruits.find().pretty()

The output is the following:

{
     "_id" : ObjectId("60f0553e1cd9041c4014a2a3"),
     "name": "apple",
     "quantity": 20
}
{
     "_id" : ObjectId("60fd8fb788fe0e2118ddbd7c"),   
     "name": "mango",
     "quantity": 20
}
{
     "_id" : ObjectId("6120216fbb75d313c4d65af4"),    
     "name": "watermelon",
     "quantity": 10
}
{
     "_id" : ObjectId("6120216fbb75d313c4d34cd3"),    
     "name": "orange",
     "quantity": 15
}

Now, let’s get fruits whose quantity is greater than 10. This will involve us using the $gt method:

db.fruits.find("quantity", {$gt : 10})

The code above will select documents with the quantity field greater than 10. The result will be as follows:

{
     "_id" : ObjectId("60f0553e1cd9041c4014a2a3"),
     "name": "apple",
     "quantity": 20
}
{
     "_id" : ObjectId("60fd8fb788fe0e2118ddbd7c"),   
     "name": "mango",
     "quantity": 20
}
{
     "_id" : ObjectId("6120216fbb75d313c4d34cd3"),    
     "name": "orange",
     "quantity": 15
}

Free Resources