![]() |
VOOZH | about |
The MongoDB $and operator combines multiple conditions in a single query and returns documents that satisfy all specified criteria, enabling precise and flexible filtering for complex queries.
Syntax:
{ $and: [ { Expression1 }, { Expression2 }, ..., { ExpressionN } ] }or
{ Expression1, Expression2, ..., ExpressionN }Use the $and operator to filter documents that must satisfy multiple conditions at the same time.
Some practical use cases and MongoDB queries that utilize the $and operator. In the following examples, we are working with:
Retrieving only those employees' documents whose branch is CSE and joiningYear is 2018.
db.contributor.find({$and: [{branch: "CSE"}, {joiningYear: 2018}]})Output:
Retrieving only those employees' documents whose branch is CSE.
db.contributor.find({$and: [{branch: {$eq: "CSE"}}, {branch: {$exists: true}}]})or
db.contributor.find({branch: {$eq: "CSE", $exists: true}})Output:
Retrieve documents where either the branch is ECE or the joining year is 2017, and either the personal.state is "Texas" or the personal.age is 25.
db.contributor.find({$and: [{ $or: [{ branch: "ECE" }, { joiningYear: 2017 }] }, { $or: [{ "personal.state": "Texas" }, { "personal.age": 25 }] }]})Output:
Some advantages are discussed below: