Document-oriented database, MongoDB is a type of NoSQL database. Different types of operators are available in MongoDB for usage when interacting with the database. In this answer, we'll learn about logical operators in MongoDB.
Logical operators are used to compare and evaluate query conditions. They work as a conjunction for joining multiple conditions. These operators are mostly used for controlling the flow of the code. They return true or false depending upon the given query.
MongoDB provides four types of logical operators:
$and
$not
$or
$nor
We'll use the following database to perform different logical operators where the database name is educative and has a collection named courses.
use educative //selecting our databasedb.courses.find({}) //query//output[{ _id: 10, course_name: 'python', hours: 10 },{ _id: 11, course_name: 'C++', hours: 15 },{ _id: 12, course_name: 'java', hours: 12 }]
Note: Learn more about comparison operators in MongoDB.
$and
operatorIt performs the logical AND operation on the expression or array of expressions. It combines two or more queries and returns the document that matches all the given conditions.
//querydb.courses.find({ $and: [{"course_name": "java"}, {"_id": {$gte: 12}}]}).pretty()//output[ { _id: 12, course_name: 'java', hours: 12 } ]
$not
operatorIt inverts the operation of a query expression. It returns the documents that fail to match the given query expression.
//querydb.courses.find({ "_id": { $not: { $gte: 11}}})//output[ { _id: 10, course_name: 'python', hours: 10 } ]
$or
operatorIt joins two or more query clauses with the logical OR operator. It returns all documents that match the conditions of either given query clause.
//querydb.courses.find({ $or: [{"course_name": "java"}, {"_id": {$eq: 11}}]}).pretty()//output[{ _id: 11, course_name: 'C++', hours: 15 },{ _id: 12, course_name: 'java', hours: 12 }]
$nor
operatorIt is the opposite of the $or
operator. It joins two or more query clauses with a logical OR operator. It returns all documents that don't match the conditions of either given query clause.
//querydb.courses.find({ $nor: [{"course_name": "java"}, {"_id": {$eq: 11}}]}).pretty()//output[ { _id: 10, course_name: 'python', hours: 10 } ]
We can run all the aforementioned MongoDB queries in the terminal below:
Free Resources