MongoDB $gt Operator

MongoDB $gt operator selects documents where the value of a field is greater than a specified value.

$gt Operator in MongoDB

The $gt operator in MongoDB is a comparison operator. It is used to find documents where the value in the field is greater than(>) a given value.

This operator can be used with other methods like find, update, etc. according to users’ requirements.

Syntax

The syntax for MongoDB $gt operator is:

{field: {$gt: value}}

MongoDB $gt Operator Examples

Let’s look at some examples of the $gt operator in MongoDB to understand it better.

In the following examples, we are working with:

Database: w3wiki
Collection: employee
Document: four documents that contain the details of the employees in the form of field-value pairs.

Example 1

In this example, we are selecting those documents where the value of the salary field is greater than 35000.

Query:

db.employee.find({salary: {$gt: 35000}}).pretty()

Output:

Example 2

In this example, we are selecting only those documents where the age of the employee is greater than 23. Or in other words, in this example, we are specifying conditions on the field in the embedded document using dot notation.

Query:

db.employee.find({"personalDetails.age": {$gt:23}}).pretty()

Output:

Using $gt operator with arrays

In this example, we are selecting only those documents where the points array is greater than the specified array.

Query:

db.employee.find({points: {$gt: [4,5]}}).pretty()

Output:

Important Points About MongoDB $gt Operator

  1. The $gt operator is used to select documents where the value of a field is greater than a specified value.
  2. It is typically used in with other query operators or as part of a query object to compare the value of a field with the specified value and return documents where the field value is greater.
  3. The $gt operator can be used with various data types, including numbers, dates, and strings, allowing for versatile data analysis tasks.
  4. The $gt operator can be used in methods like find, update, etc., to filter documents based on the specified condition.
  5. The $gt operator can be used to perform complex data analysis tasks, such as finding records above a certain threshold or retrieving documents within a specific date range.

Contact Us