Introduction to MongoDB $and Operator
The MongoDB $and
operator is used to combine multiple conditions to form a logical “AND” relationship. It can be used in conjunction with other query operators, such as $eq
, $ne
, $gt
, $lt
, etc., to build more complex query conditions.
Syntax
The $and
operator uses an array as its value, with each element of the array being a query expression that is logically related by an “AND” relationship.
Here is an example of the syntax for the $and
operator:
{ $and: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }
Use Cases
The $and
operator is useful for situations where multiple query conditions need to be met simultaneously. For example, if you want to query a collection for documents where one field is equal to a certain value and another field is greater than a certain value, you can use the $and
operator to combine the two query conditions, as shown below:
db.collection.find({ $and: [{ field1: value1 }, { field2: { $gt: value2 } }] })
Examples
Example 1
The following example shows how to use the $and
operator to query a collection for documents that meet two query conditions simultaneously.
Suppose you have a collection that stores user information, with each document containing fields for the user’s name and age. Now, suppose you want to query the collection for all users whose age is between 20 and 30 and whose name is “John”. You can use the following query statement:
db.users.find({ $and: [{ age: { $gte: 20, $lte: 30 } }, { name: "John" }] })
Running this query will return all users whose age is between 20 and 30 and whose name is “John”.
Example 2
The following example shows how to use the $and
operator to query a collection for documents that meet multiple query conditions simultaneously.
Suppose you have a collection that stores product information, with each document containing fields for the product’s name, price, and inventory. Now, suppose you want to query the collection for all products whose price is less than or equal to 500, inventory is greater than or equal to 10, and whose name does not contain the word “apple”. You can use the following query statement:
db.products.find({
$and: [
{ price: { $lte: 500 } },
{ inventory: { $gte: 10 } },
{ name: { $not: /apple/ } }
]
})
Running this query will return all products whose price is less than or equal to 500, inventory is greater than or equal to 10, and whose name does not contain the word “apple”.
Conclusion
The $and
operator can combine multiple query conditions to form a logical “AND” relationship, and can be used to query for documents that meet multiple query conditions simultaneously. Additionally, the $and
operator can be used in conjunction with other query operators to construct more complex query conditions.