mongo-db
  1. mongo-db-lt-operator

MongoDB $lt Operator

The $lt operator in MongoDB is used to compare whether a specified expression is less than 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 $lt operator in MongoDB aggregation.

Syntax

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

Example

Consider a collection named products with documents containing price and quantity fields. We want to find products whose price is less than $50.

db.products.aggregate([
  {
    $match: {
      price: { $lt: 50 }
    }
  }
]);

Output

The output will display documents from the products collection where the price is less than $50.

[
  { "_id": ObjectId("..."), "name": "Pen", "price": 0.99, "quantity": 500 },
  { "_id": ObjectId("..."), "name": "Notebook", "price": 4.99, "quantity": 200 },
  // ... other documents
]

Explanation

  • The $match stage is used to filter documents based on the condition that the price field is less than $50.

Use

The $lt 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 less than a specified value.

Important Points

  • The $lt 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 $lt operator in MongoDB is a valuable tool for filtering documents based on a less-than 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 $lt operator is crucial for MongoDB developers working with aggregation pipelines to filter and analyze data.

Published on: