9.5. Querying Documents in MongoDB: Querying Documents Using Logical Operators
In MongoDB, document querying is an essential part of interacting with the database. The query allows you to retrieve specific data from a collection of documents. This chapter will cover logical operators that can be used to perform more complex and specific queries in MongoDB.
Logical Operators
Logical operators in MongoDB are used to combine or modify conditions in a query. Logical operators include $and, $or, $not, and $nor.
$and
The $and operator performs a logical AND operation on an array of two or more expressions (e.g., { $and: [ {
$or
The $or operator performs a logical OR operation on an array of two or more { $or: [ {
$not
The $not operator performs a logical NOT operation on the expression and selects documents that do not match the expression. The $not operator must be used with expressions that use query operators. For example, the query { field: { $not: { $gt: 1.99 } } } will select all documents where the field value is not greater than 1.99.
$nor
The $nor operator performs a logical NOR operation on an array of two or more expressions and selects documents that do not match any of the expressions. The $nor operator has short-circuit evaluation. That is, if the first expression evaluated is true, MongoDB will not evaluate the remaining expressions.
Example of Query with Logical Operators
Suppose we have the following collection of documents:
{ "_id": 1, "name": "John Doe", "age": 22, "status": "A" }, { "_id": 2, "name": "Jane Doe", "age": 25, "status": "B" }, { "_id": 3, "name": "Mary Johnson", "age": 22, "status": "A" }
We can use the $and operator to find all documents where the age is 22 and the status is "A". The query would look like this:
db.collection.find( { $and: [ { age: 22 }, { status: "A" } ] } )
This will return documents where both conditions are true.
Similarly, we can use the $or operator to find all documents where the age is 22 or the status is "B". The query would look like this:
db.collection.find( { $or: [ { age: 22 }, { status: "B" } ] } )
This will return documents where at least one of the conditions is true.
In summary, logical operators in MongoDB are powerful tools that allow you to create complex and specific queries. They are essential for extracting useful information from a MongoDB database.