MongoDB $and Operator

Introduction

MongoDB provides a variety of logical query operators. The $and operator is one of those operators. The $and operator is used to perform logical AND operations on an array of one or more expressions. The user can use this operator in methods like find(), update(), etc., as per their requirements.

The user can also use "AND operation" with the help of a comma (,). The $and operator uses short-circuit evaluation. When the user specifies the same field or operator in more than one expression, then the user can use the "$AND operation".

For example, suppose two expressions (e1 and e2). If the first expression (e1) is evaluated to be false, then the second expression (e2) will not be evaluated.

Syntax:

Examples:

In the following examples, we are working with:

Matching two conditions values using $and operator:

In this example, we're only getting documents from students who meet these conditions:

  1. "Class" of the student is VI.
  2. "Sex" of the student is female.

SQL equivalent command:

Output:

MongoDB $and Operator

Note: The find() method displays the documents in a non-structured format, so it uses the pretty() method to display the results in a formatted way.

Matching multiple conditions values using $and operator:

In this example, we're only getting documents from students who meet these conditions:

  1. "Age" of the student is 17.
  2. "Sex" of the student is female.
  3. "Class" of the student is X.

SQL equivalent command:

Output:

MongoDB $and Operator




Latest Courses