MongoDB Evaluation Query Operators Example
Hello readers, in this tutorial, we will understand the different evaluation 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 (version 3.6) on Windows or Ubuntu operating system and you wish to learn the evaluation 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 Evaluation Query Operators Example
In this tutorial, we will learn how to handle the different evaluation 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 editors
. Open the Mongo terminal and execute the script.
> use warehouse > db.editors.insertMany( [ { "_id" : "1001", "name" : { "first" : "Daniel", "last" : "Atlas" }, "age" : 27, "grades" : { "JavaCodeGeek" : "A", "WebCodeGeek" : "A+", "DotNetCodeGeek" : "A" } }, { "_id" : "1002", "name" : { "first" : "Charlotte", "last" : "Neil" }, "age" : 24 }, { "_id" : "1003", "name" : { "first" : "James", "last" : "Breen" }, "age" : 17 }, { "_id" : "1004", "name" : { "first" : "John", "last" : "Gordon" }, "age" : 20 }, { "_id" : "1005", "name" : { "first" : "Rick", "last" : "Ford" }, "age" : 25, "grades" : { "JavaCodeGeek" : "A+", "WebCodeGeek" : "A+", "DotNetCodeGeek" : "A" } }, { "_id" : "1006", "name" : { "first" : "Susan", "last" : "Dixit" }, "age" : 32 }, { "_id" : "1007", "name" : { "first" : "John", "last" : "Snow" }, "age" : 21 }, { "_id" : "1008", "name" : { "first" : "Arya", "last" : "Stark" }, "age" : 25 }, { "_id" : "1009", "name" : { "first" : "April", "last" : "Paul" }, "age" : 28, "grades" : { "JavaCodeGeek" : "A+", "WebCodeGeek" : "A", "DotNetCodeGeek" : "A+" } }, { "_id" : "1010", "name" : { "first" : "Samir", "last" : "Pathak" }, "age" : 31 } ] ) > db.editors.find()
If everything goes well, the database and the collection will be shown in the Mongo Workbench.
2.1 $mod Operator
In the Mongo universe, the $mod operator allows the user to get those documents from a collection where the specific field when divided by a divisor has an even or odd remainder. This operator works like the WHERE
clause of the SQL
programming language. The $mod
operator works only on the integer values and here is what the query syntax will look like.
Syntax
> db.collection_name.find( { <field_name>: { $mod: [ divisor, remainder ] } } )
Where:
- field_name is the attribute name on which the documents are fetched from a collection
- divisor and remainder are the input arguments to perform a modulo operation
Let’s understand this with the help of an example.
Query 1
> db.editors.find( { age: { $mod: [ 5, 0 ] } } ).pretty()
This command will only get those documents from the editors
collection where the value of the age
field modulo 5
equals 0
.
2.1.1 Errors that occur with ‘$mod’ operator
Below is the list of errors that occur when the $mod
operator passed an array argument, having less or more than two elements.
- Array with Single Element
Consider the following query where the $mod
operator has an array that has a single element.
> db.editors.find( { age: { $mod: [ 5 ] } } ).pretty()
The following Mongo operation results in the below error.
Error Log
Error: error: { "ok" : 0, "errmsg" : "malformed mod, not enough elements", "code" : 2, "codeName" : "BadValue" }
Do remember, in the earlier versions of the Mongo database, if an array is passed with a single element, the $mod
operator uses the given element as the divisor and 0
as the remainder value.
- Empty Array
Consider the following query where the $mod
operator has an empty array.
> db.editors.find( { age: { $mod: [ ] } } ).pretty()
The following Mongo operation results in the below error.
Error Log
Error: error: { "ok" : 0, "errmsg" : "malformed mod, not enough elements", "code" : 2, "codeName" : "BadValue" }
- Too Many Elements Error
Consider the following query where the $mod
operator has an array with more than two elements.
> db.editors.find( { age: { $mod: [ 8, 4, 2, 1 ] } } ).pretty()
The following Mongo operation results in the below error.
Error Log
Error: error: { "ok" : 0, "errmsg" : "malformed mod, too many elements", "code" : 2, "codeName" : "BadValue" }
Do remember, in the earlier versions of the Mongo database, if an array is passed with more than two elements, the $mod
operator ignores all but the first two elements.
2.2 $regex Operator
In the Mongo universe, the $regex operator allows the user to get those documents from a collection where a string matches a specified pattern. Here is what the query syntax will look like.
Syntax
> db.collection_name.find( { <field_name>: { $regex: /pattern/, $options: '<options>' } } )
Where:
- field_name is the attribute name on which the documents are fetched from a collection
- A pattern is a regular expression for a complex search
Below table shows the different <options>
that are available in the Mongo database.
Option | Description | Syntax Restrictions |
---|---|---|
i | Allows the developers to match the upper and the lower case characters. | |
m | Allows the developers to match the patterns that include the anchor tags (i.e. ^ for the start and $ for the end). | |
x | Allows the developers to ignore all the white space characters in the $regex pattern. | Requires $regex with $options syntax |
s | Allows the dot character (i.e. . ) to match all the characters including the newline character | Requires $regex with $options syntax |
Let’s understand this with the help of an example.
Query 2
> db.editors.find( { "name.first" : { $regex: 'A.*' } } ).pretty()
This command will only get those documents from the editors
collection where the value of the first
name field must start with letter A.
2.3 $where Operator
In the Mongo universe, the $where operator allows the user to get those documents from a collection that specifies a JavaScript expression or a full JavaScript function. The JavaScript expression or the function is referred as this or obj. Here is what the query syntax will look like.
Syntax
> db.collection_name.find( { $where: <JavaScript_function> } )
Where:
- JavaScript_function is a function to test an expression
Let’s understand this with the help of an example.
Query 3
> db.editors.find( { $where: function() { return (this.name.first == "April") }}).pretty()
This command will only get those documents from the editors
collection where the first name first must be same as April
.
2.4 $text Operator
In the Mongo universe, the $text operator allows the developers to do a text search on the content of the fields indexed with a text index. Here is what the query syntax will look like.
Syntax
> db.collection_name.find( { $text: { $search: <string>, $language: <string>, $caseSensitive: <boolean>, $diacriticSensitive: <boolean> } } )
Where:
- $search is a string that Mongo database uses to query the text index
- $language is an optional parameter that determines the list of stop words for a search. If not specified, the search operation uses a default language of index
- $caseSensitive is an optional Boolean flag to enable or disable the case-sensitive search
- $diacriticSensitive is an optional Boolean flag to enable or disable the sensitive search against the text indexes
Let’s understand this with the help of an example.
Query 4
> db.editors.createIndex( { hobbies: "text" } ) > db.editors.find( { $text: { $search: "Coffee" } } ).pretty()
This command will only get those documents from the editors
collection that has the word ‘coffee ‘ in an indexed subjected field. Do note, for the ‘$text ‘ operator to work, developers need to have a text-index. In case, developers wish to learn this operator in detail, they can refer to this link.
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 evaluation 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 evaluation query operators available in the Mongo database.
You can download the full source code of this example here: MongoDbEvaluationQueryOperator
Excellent article that’s what i have been searching for.
Thank you, Mehtab! :)