Querying Documents

Learn about different query operators ($eq, $gt, $lt, $in, etc.) and how to construct complex queries to retrieve specific documents.


MongoDB Essentials: Comparison Operators

This document provides an overview of comparison operators in MongoDB, specifically focusing on $gt, $lt, $gte, $lte, and $ne. These operators are crucial for constructing range-based queries and filtering documents based on numerical, date, or string values.

Comparison Operators Explained

$gt (Greater Than)

The $gt operator selects those documents where the value of the specified field is greater than the specified value.

 db.collection.find({ field: { $gt: value } }) 

Example: Find all documents where the age field is greater than 30.

 db.users.find({ age: { $gt: 30 } }) 

$lt (Less Than)

The $lt operator selects those documents where the value of the specified field is less than the specified value.

 db.collection.find({ field: { $lt: value } }) 

Example: Find all products where the price field is less than 100.

 db.products.find({ price: { $lt: 100 } }) 

$gte (Greater Than or Equal To)

The $gte operator selects those documents where the value of the specified field is greater than or equal to the specified value.

 db.collection.find({ field: { $gte: value } }) 

Example: Find all employees where the salary field is greater than or equal to 50000.

 db.employees.find({ salary: { $gte: 50000 } }) 

$lte (Less Than or Equal To)

The $lte operator selects those documents where the value of the specified field is less than or equal to the specified value.

 db.collection.find({ field: { $lte: value } }) 

Example: Find all orders where the quantity field is less than or equal to 5.

 db.orders.find({ quantity: { $lte: 5 } }) 

$ne (Not Equal To)

The $ne operator selects those documents where the value of the specified field is not equal to the specified value.

 db.collection.find({ field: { $ne: value } }) 

Example: Find all users where the status field is not equal to "inactive".

 db.users.find({ status: { $ne: "inactive" } }) 

Range-Based Queries with Comparison Operators

Comparison operators are particularly useful when performing range-based queries. You can combine multiple comparison operators to define a range of acceptable values for a specific field.

Example: Find all products where the price is between 50 and 200 (inclusive).

 db.products.find({
                price: {
                    $gte: 50,
                    $lte: 200
                }
            }) 

Example: Find all users whose age is greater than 25 and less than 40.

 db.users.find({
                age: {
                    $gt: 25,
                    $lt: 40
                }
            })