0
0
MongoDBquery~5 mins

$and operator behavior in MongoDB

Choose your learning style9 modes available
Introduction

The $and operator helps you find documents that match all given conditions at the same time.

When you want to find people who live in a city AND are older than 30.
When you need products that are both in stock AND cost less than $20.
When searching for books that are written by a specific author AND published after 2010.
When filtering orders that are both shipped AND paid.
When you want to combine multiple filters that must all be true.
Syntax
MongoDB
{ $and: [ { condition1 }, { condition2 }, ... ] }

Each condition inside the array is a separate filter.

All conditions must be true for a document to match.

Examples
Finds documents where age is greater than 30 AND city is New York.
MongoDB
{ $and: [ { age: { $gt: 30 } }, { city: 'New York' } ] }
Finds products that cost less than 20 AND are in stock.
MongoDB
{ $and: [ { price: { $lt: 20 } }, { inStock: true } ] }
Finds books by Alice published in or after 2010.
MongoDB
{ $and: [ { author: 'Alice' }, { year: { $gte: 2010 } } ] }
Sample Program

This query finds all products in the 'electronics' category with a price less than 100.

MongoDB
db.products.find({ $and: [ { category: 'electronics' }, { price: { $lt: 100 } } ] })
OutputSuccess
Important Notes

If you only have one condition, you don't need $and because MongoDB treats it as AND by default.

Using $and is helpful when you want to combine multiple complex conditions explicitly.

Summary

$and finds documents matching all listed conditions.

Conditions are inside an array and all must be true.

Use it to combine filters that must happen together.