MongoDB – Logical Query Operators
MongoDB supports logical query operators. These operators are used for filtering the data and getting precise results based on the given conditions. The following table contains the comparison query operators:
Operator | Description |
---|---|
$and | It is used to join query clauses with a logical AND and return all documents that match the given conditions of both clauses. |
$or | It is used to join query clauses with a logical OR and return all documents that match the given conditions of either clause. |
$not | It is used to invert the effect of the query expressions and return documents that does not match the query expression. |
$nor | It is used to join query clauses with a logical NOR and return all documents that fail to match both clauses. |
In the following examples, we are working with:
Database: w3wiki 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.
db.contributor.find({$ and : [{branch: "CSE" }, {joiningYear: 2018 }]}).pretty() |
Matching values using $nor operator:
In this example, we are retrieving only those employee’s documents whose salary is not 3000 and whose branch is not ECE.
db.contributor.find({$nor: [{salary: 3000 }, {branch: "ECE" }]}).pretty() |
Matching values using $or operator:
In this example, we are retrieving only those employee’s documents whose branch is ECE or joiningYear is 2017.
db.contributor.find({$ or : [{branch: "ECE" }, {joiningYear: 2017 }]}).pretty() |
Matching values using $not operator:
In this example, we are retrieving only those employee’s documents whose salary is not greater than 2000.
db.contributor.find({salary: {$ not : {$gt: 2000 }}}).pretty() |
Contact Us