mongo-db
  1. mongo-db-gte-operator

MongoDB $gte Operator

The $gte operator in MongoDB is used to compare whether a specified expression is greater than or equal to another expression. It is commonly employed within the $match stage of an aggregation pipeline to filter documents based on a range of values. This guide will cover the syntax, examples, output, explanations, use cases, important points, and a summary of using the $gte operator in MongoDB aggregation.

Syntax

{ $match: { field: { $gte: value } } }
  • $match: Aggregation stage to filter documents.
  • field: The field on which to apply the $gte operator.
  • $gte: The operator that checks if the field value is greater than or equal to the specified value.
  • value: The value to compare against.

Example

Consider a collection named employees with documents containing salary and position fields. We want to find employees whose salary is greater than or equal to $50,000.

db.employees.aggregate([
  {
    $match: {
      salary: { $gte: 50000 }
    }
  }
]);

Output

The output will display documents from the employees collection where the salary is greater than or equal to $50,000.

[
  { "_id": ObjectId("..."), "name": "Alice", "position": "Manager", "salary": 60000 },
  { "_id": ObjectId("..."), "name": "Bob", "position": "Developer", "salary": 55000 },
  // ... other documents
]

Explanation

  • The $match stage is used to filter documents based on the condition that the salary field is greater than or equal to $50,000.

Use

The $gte operator in MongoDB is used for:

  • Filtering documents based on a range of values in the $match stage.
  • Narrowing down the result set to include only documents with field values greater than or equal to a specified value.

Important Points

  • The $gte operator is part of the rich set of comparison operators available in MongoDB.
  • It can be combined with other operators to create complex filtering conditions.

Summary

The $gte operator in MongoDB is a valuable tool for filtering documents based on a greater-than-or-equal-to condition. It is commonly used in aggregation pipelines to narrow down the result set and retrieve documents within a specific range of values. Understanding how to use the $gte operator is crucial for MongoDB developers working with aggregation pipelines to filter and analyze data.

Published on: