The Wayback Machine - https://web.archive.org/web/20241005213216/https://www.geeksforgeeks.org/mongodb-logical-query-operators/
Open In App

MongoDB – Logical Query Operators

Last Updated : 19 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Logical query operators in MongoDB are fundamental tools used to combine or modify the results of queries using logical conditions. These operators empower developers to create complex queries by combining multiple conditions and enabling precise filtering of documents based on various criteria.

In this article, We will learn about the Logical Query Operator in MongoDB by understanding various operators with examples and so on.

Logical Query Operator in MongoDB

  • Logical query operators in MongoDB are used to combine or modify the results of queries using logical conditions.
  • These operators allow us to create complex queries by combining multiple conditions.
  • Logical operators allow for the creation of complex queries that combine multiple conditions. This enables precise filtering of documents based on various criteria.
  • Logical operators can make queries more readable by clearly separating different conditions and their logical relationships.

Operators

The following table contains the various Logical Query Operators are as follows:

It Joins query clauses with a logical OR. Returns documents that match any of the conditions.

Operator Description Syntax
$and It Joins query clauses with a logical AND. Returns documents that match all the conditions. { $and: [ { <expression1> }, { <expression2> }, ... ] }
$or { $or: [ { <expression1> }, { <expression2> }, ... ] }
$nor It Joins query clauses with a logical NOR. Returns documents that fail to match all the conditions. { $nor: [ { <expression1> }, { <expression2> }, ... ] }
$not It Inverts the effect of a query expression. Returns documents that do not match the query expression. { <field>: { $not: { <operator-expression> } } }

Exampes of Logical Query Operators

This table provides a clear and concise

In the following examples, we are working with:

Database: GeeksforGeeks
Collection: contributor
Document: three documents that contain the details of the contributors in the form of field-value pairs.

Output

Example 1: 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()

Output

Example 2: 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()

Output

Example 3: 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()

Output

Example 4: 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()

Output

Matching-values-using--not-operator

Conclusion

Logical query operators in MongoDB are powerful tools for constructing complex queries that combine multiple conditions. They enable precise filtering of documents, enhancing the readability and maintainability of queries.

FAQs on Logical Query Operators

What are the logical query operators in MongoDB?

Logical query operators in MongoDB are used to combine or modify query conditions to create complex queries. The primary logical operators are $and, $or, $nor, and $not, which enable precise filtering of documents.

What is the query operator in MongoDB?

A query operator in MongoDB is a special keyword used to specify conditions in queries. These operators include comparison operators, logical operators, and element operators, enhancing the querying capabilities beyond simple equality checks.

Is it possible to nest logical query operators in MongoDB queries?

Yes, logical query operators can be nested in MongoDB queries to form complex and precise query conditions. Nesting allows combining multiple logical operators within a single query for intricate filtering logic.


Previous Article
Next Article

Similar Reads

MongoDB - Comparison Query Operators
Comparison Query Operators in MongoDB are used to filter documents based on some specific criteria within their fields. MongoDB uses various comparison query operators to compare the values of the documents. The following table contains the comparison query operators: OperatorsDescription$eqMatches the values of the fields that are equal to a speci
3 min read
Specify Validation With Query Operators in MongoDB
Validation rules in MongoDB define the structure and content requirements for collections by ensuring data integrity by allowing only valid documents to be inserted. By using query operators, MongoDB validators enforce rules such as field types, required fields and allowable values and thereby preventing invalid data from entering the database. In
5 min read
MongoDB - Field Update Operators
MongoDB, a popular NoSQL database, provides a variety of field update operators that simplify data manipulation tasks. These operators allow developers to perform specific updates on fields within documents without needing to rewrite entire documents. In this article, We will learn about the several Field Update Operators in MongoDB with the help o
5 min read
MongoDB Update Operators
MongoDB update operators offer powerful tools for modifying documents within a collection which provides flexibility and efficiency in database operations. From setting and unsetting fields to manipulating arrays and applying bitwise operations. In this article, we will understand different Update Operators which is used in MongoDB. Update Operator
6 min read
Using $search and Compound Operators in MongoDB
In MongoDB, advanced querying techniques allow users to efficiently manage and retrieve data. The $search operator is a powerful tool for performing text searches within collections while compound operators like $and, $or, and $nor enable the creation of complex queries by combining multiple conditions. In this article, We will learn about the $sea
5 min read
MongoDB - Query Documents using Mongo Shell
MongoDB provides you read operations to retrieve documents from the collection or query a collection for a document. You can perform read operations using the db.collection.find() method. This method selects or views the documents from the collection and returns the cursor to the selected document. find() is a mongo shell method, which can be used
4 min read
MongoDB - Query Embedded Documents Using Mongo Shell
MongoDB provides you read operations to retrieve embedded/nested documents from the collection or query a collection for a embedded/nested document. You can perform read operations using the db.collection.find() method. This method selects or views embedded/nested documents of the collection and returns the cursor to the selected document. Syntax:
3 min read
Python MongoDB - Update_many Query
MongoDB is a NoSQL database management system. Unlike MySQL the data in MongoDB is not stored as relations or tables. Data in mongoDB is stored as documents. Documents are Javascript/JSON like objects. More formally documents in MongoDB use BSON. PyMongo is a MongoDB API for python. It allows to read and write data from a MongoDB database using a p
3 min read
How to Query MongoDB ObjectId by Date?
MongoDB ObjectId is an important element in document identification, but can it help us with date-based queries? Understanding the ObjectId's structure and its potential for querying by date opens up new possibilities for data retrieval and analysis. In this article, We will learn about how to perform query MongoDB ObjectId by date by understanding
4 min read
Date Query with ISODate in MongoDB doesn't Seem to Work
MongoDB's ability to handle date and time values efficiently is crucial for many applications. with the help of the ISODate function, developers can query data based on precise date and time criteria. However, mastering date queries with ISODate in MongoDB requires a deep understanding of its usage and drawbacks. In this article, we'll explore prac
3 min read
How to Query MongoDB with "like"?
Querying data in MongoDB often requires pattern-matching operations similar to SQL's "LIKE" operator. While MongoDB doesn't have a direct "LIKE" operator, it offers the $regex operator and regular expressions for achieving similar functionality. In this article, We will learn about How to Query MongoDB with "like" with the help of $regex and regula
3 min read
How to Query For Is Not Null in MongoDB in a Specific Field?
MongoDB with its flexible document-oriented structure, offers powerful querying capabilities to extract meaningful insights from your data. One common requirement in database querying is to retrieve documents where a specific field is not null. In this article, We will learn about How to Query For Is Not Null in MongoDB in a Specific Field by under
4 min read
Query for Null or Missing Fields In MongoDB
MongoDB, a popular NoSQL database, offers powerful querying capabilities to retrieve data efficiently. One common requirement in database management is to search for documents where certain fields are null or missing. In MongoDB, this task can be achieved easily using various operators and methods. In this article, we will explore Query for Null or
4 min read
How to Query for Records Where Field is Null or Not Set in MongoDB?
MongoDB is a popular NoSQL database known for its flexibility and scalability. When working with MongoDB, you might encounter scenarios where you need to query for records where a specific field is either null or not set. In this article, we'll explore how to perform such queries in MongoDB, along with detailed examples to illustrate the process. U
3 min read
MongoDB Query to Find Records with Keys Containing Dots
In MongoDB, field names (or keys) in documents are strings that uniquely identify values stored within those documents. While MongoDB allows field names to contain dots (e.g., "user.name"), using keys with dots can be challenging when querying documents due to the way MongoDB interprets dots in query operations. In this article, We will learn about
4 min read
How to Perform Query Optimization in MongoDB?
MongoDB is a popular NoSQL database that offers high performance, high availability, and easy scalability. However, like any database, query performance can degrade if not properly optimized. This article will guide you through several techniques to optimize your MongoDB queries, ensuring they run efficiently and effectively. Table of Content Under
3 min read
What is a MongoDB Query?
MongoDB Query is a fundamental aspect of MongoDB that allows users to fetch data from the database. Similar to SQL queries in traditional databases, MongoDB queries provide simplicity and flexibility in retrieving specific data based on certain criteria or conditions. In this article, We will learn about the MongoDB Query in detail by performing va
6 min read
How to Make a Synchronous MongoDB Query in NodeJS?
MongoDB is a popular NoSQL database that is often used in modern web development. It is known for its flexibility, scalability, and ease of use. Node.js, with its non-blocking, event-driven architecture, is a natural fit for MongoDB. However, working with asynchronous code can sometimes be challenging. In this article, we'll explore how to make syn
2 min read
MongoDB Query an Array
MongoDB is an open-source document, NoSQL database that stores the data in a document-oriented structure. With the help of MongoDB, we can handle large, complex, and unstructured data efficiently because MongoDB is widely used for Scalability and Flexibility. In this article, we will learn about the Array Element and How to query array elements in
10 min read
How to Query for Documents Where Array Size is Greater Than 1 in MongoDB
MongoDB's flexibility in managing arrays within documents is invaluable for modern applications. Sometimes, we might need to find documents where an array field contains more than one element. Here’s how you can achieve this using MongoDB queries In this article, We will various methods through which we can easily learn How to Query for Documents W
4 min read
Query Modifiers in MongoDB
Query modifiers in MongoDB are essential tools that adjust the behavior of queries to achieve various objectives such as shaping results, enhancing performance and efficiently retrieving documents from the database. These operators allow developers to manipulate query results for tasks like sorting, projection and making queries more effective and
6 min read
How to Query MongoDB Documents with Regex in Python?
MongoDB is a popular NoSQL database known for its flexibility and scalability. One of its powerful features is the ability to query documents using regular expressions (regex) in Python. Regex allows you to perform pattern-based searches within your MongoDB collections, providing a flexible and efficient way to retrieve data. In this article, we'll
4 min read
MongoDB Query with Case Insensitive Search
In MongoDB, data is stored in documents using BSON format by consisting of key-value pairs. When performing searches, MongoDB provides flexibility in handling case sensitivity. In this article, we will explore how to perform case-insensitive searches Query in MongoDB using the $regex operator and the 'i' flag with the find() method in detail by und
5 min read
How To Query For Documents In MongoDB Using NodeJS?
MongoDB is the popular NoSQL database that allows for flexible and scalable data storage. NodeJS and JavaScript runtime built on Chrome's V8 JavaScript engine. It is often used with MongoDB to build powerful and efficient applications. In this article, we will guide you on how to query the documents in MongoDB using Node.js. We will cover the vario
4 min read
MongoDB Query and Projection Operator
MongoDB query operators are essential tools for interacting with data stored in MongoDB collections. Similar to SQL, MongoDB offers a range of operators to perform various operations such as comparisons, logical evaluations, and array manipulations. These operators allow users to efficiently query, filter, and manipulate data based on specific cond
11 min read
Dynamic Query in Java Spring Boot with MongoDB
Most of today’s applications require great flexibility regarding database querying. MongoDB provides an effective option for solving complex queries using this kind of storage for documents. Integrating it with Spring Boot makes things even smoother. In this article, we will look at how to create dynamic queries in a Spring Boot application using M
4 min read
Connect MongoDB (AWS) from Local Machine using WinSCP and MongoDB Compass
Pre-requisite: AWS and MongoDB In this article, we are going to connect to the Mongo database of the AWS Ubuntu Server instance using WinSCP and learn how to get connected to the server from your local machine using MongoDB Compass.  If you haven't installed a MongoDB server in your AWS EC2 instance then follow the steps present in this article and
4 min read
How to Integrate MongoDB Atlas and Segment using MongoDB Stitch
Data integration has become a crucial component of modern business strategies, allowing companies to enhance the power of data for informed decision-making. According to a recent survey, 85% of businesses believe that integrating data across multiple platforms is important for their success. In this article, We will learn about What is MongoDB Stit
5 min read
MongoDB - Delete Multiple Documents Using MongoDB Shell
The db.collection.deleteMany() method is used to delete multiple documents from a collection in Mongo Shell. This method deletes multiple documents from the collection according to the filter. The deleteMany() is a Mongo shell method, which can delete multiple documents. This method can be used in multi-document transactions. If you use this method
2 min read
Connect MongoDB Atlas Cluster to MongoDB Compass
MongoDB Compass is a free GUI for MongoDB. You might want to connect MongoDB Atlas Cluster to MongoDB Compass to take benefit of the GUI model for database administration. This guide explains how to connect MongoDB Atlas Cluster to MongoDB Compass. The connection process involves obtaining a connection string from MongoDB Atlas, configuring MongoDB
4 min read