mongo-db
  1. mongo-db-and-operator

$and Operator - (MongoDB Misc)

In MongoDB, the $and operator performs a logical AND operation on an array of two or more expressions and selects the documents that satisfy all the expressions in the array. In this page, we'll explore how to use $and operator in MongoDB.

Syntax

The basic syntax of the $and operator is as follows:

{ $and: [ { expr1 }, { expr2 }, ... , { exprN } ] }

Here the $and operator takes an array of expressions as its value and returns true if all expressions in the array are true.

Example

Let's say we have a collection named books with the following documents:

{ "_id" : 1, "title" : "Programming in C", "author" : "John Doe", "publisher" : "ABC Publications", "price" : 25 }
{ "_id" : 2, "title" : "Programming in Java", "author" : "Jane Smith", "publisher" : "XYZ Publications", "price" : 35 }
{ "_id" : 3, "title" : "Web Development with Node.js", "author" : "John Doe", "publisher" : "ABC Publications", "price" : 40 }

Now, let's find all the books with the author name as "John Doe" and the price less than or equal to 30. We can use the $and operator to achieve this as follows:

db.books.find({
    $and: [
        { author: "John Doe" },
        { price: { $lte: 30 } }
    ]
})

This will return the following result:

{ "_id" : 1, "title" : "Programming in C", "author" : "John Doe", "publisher" : "ABC Publications", "price" : 25 }

Output

The output of the $and operator is a cursor object that contains the documents that satisfy all the expressions in the array passed to the $and operator.

Explanation

The $and operator is very useful when we want to search for documents that match multiple criteria. We can pass any number of expressions to the $and operator, and it will return only the documents that satisfy all the expressions in the array.

In the above example, we used the $and operator to find all the books with the author name as "John Doe" and the price less than or equal to 30.

Use

We use the $and operator in MongoDB to perform a logical AND operation on an array of two or more expressions and select the documents that satisfy all the expressions in the array.

The $and operator is useful when we want to search for documents that match multiple criteria.

Important Points

  • The $and operator performs a logical AND operation on an array of two or more expressions and selects the documents that satisfy all the expressions in the array.
  • We can pass any number of expressions to the $and operator, and it will return only the documents that satisfy all the expressions in the array.

Summary

In this page, we discussed the $and operator in MongoDB, which is used to perform a logical AND operation on an array of two or more expressions and select the documents that satisfy all the expressions in the array. We covered the syntax, example, output, explanation, use, and important points of the $and operator.

Published on: