MongoDB Element Query Operators Example
Hello readers, in this tutorial, we will understand the different element 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 element query operators then follow the below steps. But before we start, 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 Element Query Operators Example
In this tutorial, we will learn how to handle the different element 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" }, "author_for" : [ "Java Code Geek", "Web Code Geek" ], "retirement_date" : "2023-01-30", address: "2030 Martian Way", zip_code : 93749834 }, { "_id" : "1002", "name" : { "first" : "Charlotte", "last" : "Neil" }, "author_for" : [ "Web Code Geek" ], post_reviews_percentage: 87.333333333333333 }, { "_id" : "1003", "name" : { "first" : "James", "last" : "Breen" }, "author_for" : [ "Java Code Geek", "Web Code Geek", "Dot Net Geek" ], "retirement_date" : "2020-12-04" }, { "_id" : "1004", "name" : { "first" : "John", "last" : "Gordon" }, "author_for" : [ "Dot Net Geek" ], "retirement_date" : "2025-05-15" }, { "_id" : "1005", "name" : { "first" : "Rick", "last" : "Ford" }, "author_for" : [ "Web Code Geek", "Dot Net Geek" ], address : "2324 Pluto Place", zip_code : "9069" }, { "_id" : "1006", "name" : { "first" : "Susan", "last" : "Dixit" }, "author_for" : [ ], "retirement_date" : "2020-12-22", post_reviews_percentage: "94.06" }, { "_id" : "1007", "name" : { "first" : "John", "last" : "Snow" }, "author_for" : [ "Java Code Geek" ], address: "156 Lunar Place", zip_code : 43339214 }, { "_id" : "1008", "name" : { "first" : "Arya", "last" : "Stark" }, "author_for" : [ "Java Code Geek", "Dot Net Geek" ], "retirement_date" : "", address : "55 Saturn Ring", zip_code : "1412" } ] ) > db.editors.find()
If everything goes well, the database and the collection will be shown in the Mongo Workbench.
2.1 $exists Operator
In the Mongo universe, the $exists operator allows the user to get those documents from a collection for which a specific field exists in a Mongo document or not. Here is what the query syntax will look like.
Syntax
> db.collection_name.find( { <field_name>: { $exists: <boolean_value> } } )
Where:
- field_name is the attribute name on which the documents from a collection are retrieved
- If the boolean_value is ‘true’,
$exists
operator matches the collection documents that contain the specific field, including documents where thefield_value
is ‘null’ - If the boolean_value is ‘false’,
$exists
operator returns those documents that do not contain the specific field
Let’s understand this with the help of an example.
2.1.1 $exists operator with ‘true’ keyword
Consider a scenario where developers want to fetch the documents from a collection where the retirement_date
field exists. The following Mongo query can be used.
Query 1
> db.editors.find( { retirement_date: { $exists: true } } ).pretty()
This command will only get those documents from the editors
collection that contain the retirement_date
field. This command also includes the document whose retirement_date
field has a blank value.
2.1.2 $exists operator with ‘false’ keyword
Consider a scenario where developers want to fetch the documents from a collection where the retirement_date
field does not exist. The following Mongo query can be used.
Query 2
> db.editors.find( { retirement_date: { $exists: false } } ).pretty()
This command will only get those documents from the editors
collection that do not contain the retirement_date
field.
2.2 $type Operator
In the Mongo universe, the $type operator allows the developers to get only those documents from a collection that have a field value of a certain data type. This operator is useful where the data-type of the data is not known. Here is what the query syntax will look like.
Syntax
> db.collection_name.find( { <field_name>: { $type: < BSON_Type> } } )
Do note, this operator also accepts an array of BSON types and has the following query syntax.
> db.collection_name.find( { <field_name>: { $type: [ <BSON_type_1>, <BSON_type_2>, . . . . . ] } } )
2.2.1 Data types in Mongo
Below table shows the different codes and string aliases available in the Mongo database for the BSON types.
Data-type | Code | Alias | |
---|---|---|---|
Double | 1 | “double” | |
String | 2 | “string” | |
Object | 3 | “object” | |
Array | 4 | “array” | |
Binary data | 5 | “binData” | |
Undefined | 6 | “undefined” | Deprecated |
ObjectId | 7 | “objectId” | |
Boolean | 8 | “bool” | |
Date | 9 | “date” | |
Null | 10 | “null” | |
Regular Expression | 11 | “regex” | |
DBPointer | 12 | “dbPointer” | Deprecated |
JavaScript | 13 | “javascript” | |
Symbol | 14 | “symbol” | Deprecated |
JavaScript (with scope) | 15 | “javascriptWithScope” | |
32-bit integer | 16 | “int” | |
Timestamp | 17 | “timestamp” | |
64-bit integer | 18 | “long” | |
Decimal128 | 19 | “decimal” | New in version 3.4 |
Min key | -1 | “minKey” | |
Max key | 127 | “maxKey” |
Let’s understand this with the help of an example.
2.2.2 $type operator with alias ‘string’
Consider a scenario where developers want to fetch the documents from a collection where the zip_code
is the “string” BSON type. The following Mongo query can be used.
Query 3
> db.editors.find( { zip_code: { $type: "string" } } ).pretty()
This command will only get those documents from the editors
collection where the zip_code
is the BSON type string.
2.2.3 $type operator with alias ‘double’
Consider a scenario where developers want to fetch the documents from a collection where the zip_code
is the “double” BSON type. The following Mongo query can be used.
Query 4
> db.editors.find( { zip_code: { $type: "double" } } ).pretty()
This command will only get those documents from the editors
collection where the zip_code
is the BSON type double.
2.2.4 $type operator with alias ‘double’ and ‘string’
Consider a scenario where developers want to fetch the documents from a collection containing the field value as post_reviews_percentage
. The following Mongo query can be used.
Query 5
> db.editors.find( { post_reviews_percentage: { $type : [ "string" , "double" ] } } ).pretty()
This command will only get those documents from the editors
collection where the post_reviews_percentage
is the BSON types string and double.
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 element 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 element query operators available in the Mongo database.
You can download the full source code of this example here: MongoDbElementQueryOperators
Nice article, but the download only contain 2 txt files
Thank you for your comment. The text files contain the steps of the sample collection creation and commands which can be executed as a part of this tutorial.