0
0
MongodbHow-ToBeginner · 3 min read

How to Use $and Operator in MongoDB Queries

In MongoDB, the $and operator is used to combine multiple query conditions that all must be true for a document to match. You use it by passing an array of conditions inside $and, like { $and: [condition1, condition2] }.
📐

Syntax

The $and operator takes an array of conditions. Each condition is a query expression. MongoDB returns documents that satisfy all these conditions.

Structure:

  • { $and: [condition1, condition2, ...] }

Each condition is a standard MongoDB query filter.

json
{
  "$and": [
    { "field1": "value1" },
    { "field2": { "$gt": "value2" } }
  ]
}
💻

Example

This example finds all documents in the products collection where the category is "books" and the price is less than 20.

mongodb
db.products.find({
  $and: [
    { category: "books" },
    { price: { $lt: 20 } }
  ]
})
Output
[ { "_id": 1, "category": "books", "price": 15, "title": "Learn MongoDB" }, { "_id": 3, "category": "books", "price": 10, "title": "MongoDB Basics" } ]
⚠️

Common Pitfalls

Many beginners try to use multiple conditions without $and inside the same object, which MongoDB treats as an implicit AND. However, when conditions target the same field, $and is necessary.

For example, to find documents where age is greater than 20 and less than 30, you must use $and because both conditions apply to the same field.

mongodb
/* Incorrect: This overwrites the age condition */
db.users.find({ age: { $gt: 20 }, age: { $lt: 30 } })

/* Correct: Use $and to combine conditions on the same field */
db.users.find({
  $and: [
    { age: { $gt: 20 } },
    { age: { $lt: 30 } }
  ]
})
📊

Quick Reference

OperatorDescriptionExample
$andMatches documents that satisfy all conditions{ $and: [ {a:1}, {b:2} ] }
Implicit ANDMultiple conditions on different fields can be combined without $and{ a:1, b:2 }
Use $andRequired when multiple conditions apply to the same field{ $and: [ {age: {$gt:20}}, {age: {$lt:30}} ] }

Key Takeaways

Use $and to combine multiple conditions that all must be true.
When filtering on the same field with multiple conditions, always use $and.
MongoDB allows implicit AND by listing conditions on different fields without $and.
The $and operator takes an array of query expressions.
Use $and to make queries clear and avoid overwriting conditions.