0
0
MongoDBquery~5 mins

Combining comparison operators in MongoDB

Choose your learning style9 modes available
Introduction

We combine comparison operators to find data that meets multiple conditions at the same time.

Finding products priced between two amounts.
Getting users who joined after a date and have a certain status.
Selecting orders with quantity greater than 5 but less than 20.
Filtering events that happened before a date and have a specific type.
Syntax
MongoDB
{ field: { $operator1: value1, $operator2: value2 } }
Use curly braces inside the field to combine multiple comparison operators.
Each operator starts with a $ sign, like $gt (greater than) or $lt (less than).
Examples
Finds documents where age is greater than 18 and less than 30.
MongoDB
{ age: { $gt: 18, $lt: 30 } }
Finds documents where price is between 10 and 50, including 10 and 50.
MongoDB
{ price: { $gte: 10, $lte: 50 } }
Finds documents where score is not equal to 100 and less than 90.
MongoDB
{ score: { $ne: 100, $lt: 90 } }
Sample Program

This query finds all products with a price greater than 20 and less than 100.

MongoDB
db.products.find({ price: { $gt: 20, $lt: 100 } })
OutputSuccess
Important Notes

Combining operators inside one field means all conditions must be true for that field.

You cannot combine conflicting operators like $gt: 10 and $lt: 5 because no value can satisfy both.

Summary

Combine comparison operators inside a field to filter data with multiple conditions.

Use $gt, $lt, $gte, $lte, $ne to compare values.

All combined conditions must be true for a document to match.