Open In App

MongoDB AND operator ( $and )

MongoDB provides different types of logical query operators and $and operator is one of them. This operator is used to perform logical AND operation on the array of one or more expressions and select or retrieve only those documents that match all the given expression in the array. You can use this operator in methods like find(), update(), etc. according to your requirements.

Syntax: 



{ $and: [ { Expression1 }, { Expression2 }, ..., { ExpressionN } ] }
or
{ { Expression1 }, { Expression2 }, ..., { ExpressionN }}

Examples: In the following examples, we are working with:

Database: GeeksforGeeks Collection: contributor Document: three documents that contain the details of the contributors in the form of field-value pairs.



Matching values using $and operator:

In this example, we are retrieving only those employee’s documents whose branch is CSE and joiningYear is 2018. 




db.contributor.find({$and: [{branch: "CSE"},
                            {joiningYear: 2018}]}).pretty()

Using $and operator with multiple expressions specifying the same field :

In this example, we are retrieving only those employee’s documents whose branch is CSE. 




db.contributor.find({$and: [{branch: {$eq: "CSE"}},
                            {branch: {$exists: true}}]}).pretty()

or 




db.contributor.find({branch: {$eq: "CSE", $exists: true}}).pretty()

Using $and operator with multiple expressions specifying the same operator :

In this example, we are retrieving only those employee’s documents whose satisfy the given conditions. 




db.contributor.find({$and: [{$or: [{branch: "ECE"}, {joiningYear: 2017}]},
                            {$or: [{"personal.state": "UP"},
                                   {"personal.age": 25}]}]}).pretty()


Article Tags :