MongoDB Logical Query Operators Example
Hello readers, in this tutorial, we will understand the different logical query operators available in the Mongo database. Let’s study in brief the different ways in which these operators can be used.
1. Introduction
If you have installed the MongoDB application on Windows or Ubuntu operating system and you wish to learn the logical query operators then follow the below steps. It is very simple, but before moving further let’s take a look at MongoDB and its features.
1.1 What is MongoDB?
- MongoDB is a high-performance NoSQL database where each database has collections which in turn has documents. Each document has a different number of fields, size, content, and is stored in a JSON-like format (i.e. Binary JSON (BSN)
- The documents in MongoDB doesn’t need to have a schema defined beforehand. Instead, the fields (i.e. records) can be created on the go
- Data model available within the MongoDB allows developers to represent the hierarchical relationships, store arrays, and other more complex structures easily
- This NoSQL solution often comes with embedding, auto-sharding, and onboard replication for better scalability and high availability
1.2 Why MongoDB?
- As a NoSQL type database, MongoDB stores the data in the form of a document. Thus, MongoDB offers more flexibility
- This database supports search by field-name, range queries, and the regular expressions. It often provides queries to return the particular fields inside the documents
- MongoDB offers indexes to improve the search performance within the NoSQL database
- To offer horizontal scalability, MongoDB uses sharding by splitting the data across the many MongoDB occurrences
- Replication: MongoDB can give high availability with the replica sets
2. MongoDB Logical Query Operators Example
In this tutorial, we will learn how to handle the different logical query operators provided by the Mongo database. But before moving further with the tutorial, we will need to create the sample collection. The following script creates a database called warehouse
with a collection as garden
. Open the Mongo terminal and execute the script.
> use warehouse > db.garden.insertMany( [ { "Name" : "Apple", "attrs" : [ "red", "fruit", "round" ] }, { "Name" : "Mongo", "attrs" : [ "red", "fruit", "round" ] }, { "Name" : "Guava", "attrs" : [ "green", "fruit", "leaf" ] }, { "Name" : "Tomato", "attrs" : [ "red", "vegetable", "round" ] }, { "Name" : "Lettuce", "attrs" : [ "green", "vegetable", "leaf" ] }, { "Name" : "Potato", "attrs" : [ "yellow", "vegetable", "round" ] } ] ); > db.garden.find()
If everything goes well, the database and the collection will be shown in the Mongo Workbench.
2.1 $and Operator
In the Mongo universe, the $and operator performs on an array of two or more expressions (e.g., <Expression 1>
, <Expression 2>
etc.). This operator is similar to a logical AND operation and gets the documents from a collection which fulfill all the expressions in an array. This operator uses the short-circuit evaluation and thus, if the first expression (i.e. <Expression 1>
) evaluates to false, the Mongo database will not check the remaining expressions. Here is what the query syntax will look like.
Syntax
> db.collection_name.find( { $and: [ { }, { } , ... , { } ] } )
Where:
- Expression 1 to ‘n’ is the array of expressions on which a logical ‘AND’ operation is performed
Let’s understand this with the help of an example.
> db.garden.find( { $and: [ {"attrs": "red"}, {"attrs": "round"} ] } ).pretty()
This command will only get those documents from the garden
collection where the value of the attrs field matches the given values i.e. red
and round
.
2.2 $not Operator
In the Mongo universe, the $not operator performs a logical NOT operation on the specified <operator-expression>
and gets the documents from a collection that:
- Do not match the
<operator-expression>
- Do not contain the field given by the
<operator-expression>
Here is what the query syntax will look like.
Syntax
> db.collection_name.find( { field_name: { $not: { <operator-expression> } } } )
Where:
- field_name is the attribute name on which the document is retrieved
- operator-expression is the condition on which a logical ‘NOT’ operation is performed
Let’s understand this with the help of an example.
> db.garden.find( { attrs: { $not : /^red.*/ } } ).pretty()
This command will only get those documents from the garden
collection where the value of the attrs field does not match the given value i.e. red
.
Do remember:
- From the above expression, we can say that the
$not
operator does not support the $regex operations. Instead, developers will have to use the ‘//
‘ - The
$not
operator can’t work alone, thus developers have to use this operator in association with the other operators i.e.,> db.sample_collection_name.find( { product_price: { $not : { $gt: 50 } } } ).pretty()
2.3 $nor Operator
In the Mongo universe, the $nor operator performs on an array of two or more expressions (e.g., <Expression 1>
, <Expression 2>
etc.). This operator is similar to a logical NOR operation and gets the documents from a collection that fail all the expressions in an array. Here is what the query syntax will look like.
Syntax
> db.collection_name.find( { $nor: [ { }, { } , ... , { } ] } )
Where:
- Expression 1 to ‘n’ is the array of expressions on which a logical ‘NOR’ operation is performed
Let’s understand this with the help of an example.
> db.garden.find( { $nor: [ {"attrs": "red"}, {"attrs": "green"} ] } ).pretty()
This command will only get those documents from the garden
collection where the value of the attrs field does not match all the given values i.e. red
and green
.
2.4 $or Operator
In the Mongo universe, the $or operator performs on an array of two or more expressions (e.g., <Expression 1>
, <Expression 2>
etc.). This operator is similar to a logical OR operation and gets the documents from a collection that satisfy at-least one of the expressions in an array. Here is what the query syntax will look like.
Syntax
> db.collection_name.find( { $or: [ { }, { } , ... , { } ] } )
Where:
- Expression 1 to ‘n’ are the array of expressions on which a logical ‘OR’ operation is performed
Let’s understand this with the help of an example.
> db.garden.find( { $or: [ {"attrs": "purple"}, {"attrs": "green"}, {"attrs": "blue"} ] } ).pretty()
This command will only get those documents from the garden
collection where the value of the attrs field matches any one of the given values i.e. purple
, green
or blue
.
Do note, the pretty()
method used in above commands displays the documents in a structured pattern. If developers want to display the output in a non-structured pattern, they can simply remove this method. That’s all for this post. Happy Learning!!
3. Conclusion
In this tutorial, we learned about the different logical query operators of the Mongo database. Developers can download the sample commands in the Downloads section.
4. Download the Eclipse Project
This was an example of the different logical query operators available in the Mongo database.
You can download the full source code of this example here: MongoDbLogicalQueryOperatorsExample