Open In App
Related Articles

MongoDB AND operator ( $and )

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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.

  • This operator performs short-circuit evaluation.
  • If the first expression of $and operator evaluates to false, then MongoDB will not evaluate the remaining expressions in the array.
  • You can also use AND operation implicitly with the help of comma(, ).
  • You can use AND operation explicitly (i.e., $and) when the same field or operator specified in multiple expressions.

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. 

Python3

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. 

Python3

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

                    

or 

Python3

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. 

Python3

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

                    



Last Updated : 05 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads