0
0
MongoDBquery~5 mins

Why logical operators matter in MongoDB

Choose your learning style9 modes available
Introduction

Logical operators help you combine multiple conditions to find exactly what you want in your data.

You want to find documents that match several conditions at the same time.
You want to find documents that match at least one of several conditions.
You want to exclude documents that meet certain conditions.
You want to create complex filters by mixing conditions with AND, OR, and NOT.
You want to make your searches more precise and flexible.
Syntax
MongoDB
{ $and: [ { condition1 }, { condition2 } ] }
{ $or: [ { condition1 }, { condition2 } ] }
{ $not: { condition } }

$and means all conditions must be true.

$or means at least one condition must be true.

$not means the condition must NOT be true.

Examples
Finds documents where age is greater than 18 AND city is New York.
MongoDB
{ $and: [ { age: { $gt: 18 } }, { city: 'New York' } ] }
Finds documents where status is active OR score is at least 90.
MongoDB
{ $or: [ { status: 'active' }, { score: { $gte: 90 } } ] }
Finds documents where age is NOT less than 18.
MongoDB
{ age: { $not: { $lt: 18 } } }
Sample Program

This query finds students who have grade 'A' AND attendance of 90 or more.

MongoDB
db.students.find({ $and: [ { grade: 'A' }, { attendance: { $gte: 90 } } ] })
OutputSuccess
Important Notes

Logical operators can be combined to build complex queries.

Using them correctly helps you get precise results and saves time.

Summary

Logical operators combine conditions to filter data.

$and requires all conditions to be true.

$or requires at least one condition to be true.

$not excludes documents matching a condition.