Advanced Indexing in MongoDB and Limitation of Indexing in MongoDB

Last updated on May 30 2022
Satyen Sahu

Table of Contents

Advanced Indexing in MongoDB and Limitation of Indexing in MongoDB

MongoDB – Advanced Indexing

Consider the subsequent document of the users collection −
{
“address”: {
“city”: “Los Angeles”,
“state”: “California”,
“pincode”: “123”
},
“tags”: [
“music”,
“cricket”,
“blogs”
],
“name”: “Tom Benzamin”
}
The above document contains an address sub-document and a tags array.

Indexing Array Fields

Suppose we want to search user documents based on the user’s tags. For this, we will create an index on tags array in the collection.
Creating an index on array in turn creates separate index entries for every of its fields. So in our case when we create an index on tags array, separate indexes will be created for its values music, cricket and blogs.
To create an index on tags array, use the subsequent code −
>db.users.ensureIndex({“tags”:1})
After creating the index, we can search on the tags field of the collection like this −
>db.users.find({tags:”cricket”})
To verify that proper indexing is used, use the subsequent explain command −
>db.users.find({tags:”cricket”}).explain()
The above command resulted in “cursor” : “BtreeCursor tags_1” which confirms that proper indexing is employed.

Indexing Sub-Document Fields

Suppose that we want to search documents based on city, state and pincode fields. Since all these fields are part of address sub-document field, we will create an index on all the fields of the sub-document.
For creating an index on all the three fields of the sub-document, use the subsequent code −
>db.users.ensureIndex({“address.city”:1,”address.state”:1,”address.pincode”:1})
Once the index is created, we can search for any of the sub-document fields utilizing this index as follows −
>db.users.find({“address.city”:”Los Angeles”})
Remember that the query expression has got to follow the order of the index specified. Therefore the index created above would support the subsequent queries −
>db.users.find({“address.city”:”Los Angeles”,”address.state”:”California”})
It will also support the subsequent query −
>db.users.find({“address.city”:”LosAngeles”,”address.state”:”California”,
“address.pincode”:”123″})

MongoDB – Indexing Limitations

In this chapter, we’ll learn about Indexing Limitations and its other components.
Extra Overhead
Every index occupies some space also as causes an overhead on every insert, update and delete. So if you rarely use your collection for read operations, it makes sense not to use indexes.
RAM Usage
Since indexes are stored in RAM, you ought to confirm that the entire size of the index doesn’t exceed the RAM limit. If the entire size increases the RAM size, it’ll start deleting some indexes, causing performance loss.
Query Limitations
Indexing can’t be used in queries which use −
• Regular expressions or negation operators like $nin, $not, etc.
• Arithmetic operators like $mod, etc.
• $where clause
Hence, it is always advisable to check the index usage for your queries.
Index Key Limits
Starting from version 2.6, MongoDB will not create an index if the value of existing index field exceeds the index key limit.
Inserting Documents Exceeding Index Key Limit
MongoDB will not insert any document into an indexed collection if the indexed field value of this document exceeds the index key limit. Same is the case with mongorestore and mongoimport utilities.
Maximum Ranges
• A collection can’thave more than 64 indexes.
• The length of the index name can’tbe longer than 125 characters.
• A compound index can have maximum 31 fields indexed.

MongoDB – ObjectId

In this section, we will understand the structure of ObjectId.
An ObjectId may be a 12-byte BSON type having the subsequent structure −
• The first 4 bytes representing the seconds since the unix epoch
• The next 3 bytes are the machine identifier
• The next 2 bytes consists of process id
• The last 3 bytes are a random counter value
MongoDB uses ObjectIds because the default value of _id field of every document, which is generated while the creation of any document. The complex combination of ObjectId makes all the _id fields unique.

Creating New ObjectId

To generate a new ObjectId use the subsequent code −
>newObjectId = ObjectId()
The above statement returned the subsequent uniquely generated id −
ObjectId(“5349b4ddd2781d08c09890f3”)
Instead of MongoDB generating the ObjectId, you can also provide a 12-byte id −
>myObjectId = ObjectId(“5349b4ddd2781d08c09890f4”)

Creating Timestamp of a Document

Since the _id ObjectId by default stores the 4-byte timestamp, in most cases you do not need to store the creation time of any document. You’ll fetch the creation time of a document using getTimestamp method −
>ObjectId(“5349b4ddd2781d08c09890f4”).getTimestamp()
This will return the creation time of this document in ISO date format −
ISODate(“2014-04-12T21:49:17Z”)

Converting ObjectId to String

In some cases, you’ll need the worth of ObjectId in a string format. To convert the ObjectId in string, use the subsequent code −
>newObjectId.str
The above code will return the string format of the Guid −
5349b4ddd2781d08c09890f3

So, this brings us to the end of blog. This Tecklearn ‘Advanced Indexing in MongoDB and Limitation of Indexing in MongoDB’ helps you with commonly asked questions if you are looking out for a job in MongoDB and No-SQL Database Domain.
If you wish to learn and build a career in MongoDB or No-SQL Database domain, then check out our interactive, MongoDB Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

MongoDB Training

MongoDB Training

About the Course

Tecklearn’s MongoDB Training helps you to master the NoSQL database. The course makes you job-ready by letting you comprehend schema design, data modelling, replication, and query with MongoDB through real-time examples. Along with this, you’ll also gain hands-on expertise in installing, configuring, and maintaining the MongoDB environment, including monitoring and operational strategies from this online MongoDB training. Upon completion of this online training, you will hold a solid understanding and hands-on experience with MongoDB.

Why Should you take MongoDB Training?

• MongoDB – a $36 billion to a $40 billion market growing at 8% to 9% annually – Forbes.com
• Average salary of a Mongo DB certified professional is $134k – Indeed.com
• MongoDB has more than 900 customers, including 27 Fortune 100 companies like Cisco, eBay, eHarmony, MetLife & Salesforce.com

What you will Learn in this Course?

Introduction to MongoDB and Importance of NoSQL
• Understanding the basic concepts of RDBMS
• What is NoSQL Database and its significance?
• Challenges of RDBMS and How NoSQL suits Big Data needs
• Types of NoSQL Database and NoSQL vs. SQL Comparison
• CAP Theorem and Implementing NoSQL
• Introduction to MongoDB and its advantages
• Design Goals for MongoDB Server and Database, MongoDB tools
• Collection, Documents and Key Value Pair
• Introduction to JSON and BSON documents
• MongoDB installation
MongoDB Installation
• MongoDB Installation
• Basic MongoDB commands and operations,
• Mongo Chef (MongoGUI) Installation
Schema Design and Data Modelling
• Why Data Modelling?
• Data Modelling Approach
• Data Modelling Concepts
• Difference between MongoDB and RDBMS modelling
• Challenges for Data Modelling
• Model Relationships between Documents
• Data Model Examples and Patterns
• Model Tree Structures
CRUD Operations
• MongoDB Architecture
• CRUD Introduction and MongoDB CRUD Concepts
• MongoDB CRUD Concerns (Read and Write Operations)
• Cursor Query Optimizations and Query Behaviour in MongoDB
• Distributed Read and Write Queries
• MongoDB Datatypes
Indexing and Aggregation Framework
• Concepts of Data aggregation and types and data indexing concepts
• Introduction to Aggregation
• Approach to Aggregation
• Types of Aggregation: Pipeline, MapReduce and Single Purpose
• Performance Tuning
MongoDB Administration
• Administration concepts in MongoDB
• MongoDB Administration activities: Health check, recovery, backup, database sharing and profiling, performance tuning etc.
• Backup and Recovery Methods for MongoDB
• Export and Import of Data from MongoDB
• Run time configuration of MongoDB
MongoDB Security
• Security Introduction
• MongoDB security Concepts and security approach
• MongoDB integration with Java and Robomongo
Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Advanced Indexing in MongoDB and Limitation of Indexing in MongoDB"

Leave a Message

Your email address will not be published. Required fields are marked *