What is the $lt Operator in MongoDB?

Overview

The $lt operator is a comparison operator in MongoDB that is used to match values that are less than a specified value.

$lt is used to match documents that have a field value that is less than the specified value.

Syntax

Let’s view the syntax of the $lt operator.

{field: {$lt: value}}

Parameters

  • field: a valid document path.
  • value: the value to compare with document field values.

Return value

The $lt operator returns documents with field values less than the specified value.

Code example

Let’s say we have a fruits collection that has the following documents.

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

Now, let’s use the $lt operator to query and match documents that have a quantity less than 20.

db.fruits.find("quantity", {$lt : 20})

The output of the query above will be as follows:

{
"_id" : ObjectId("6120216fbb75d313c4d65af4"),
"name": "watermelon",
"quantity": 10
}

Free Resources