EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

Indexes in MongoDB

Home » Data Science » Data Science Tutorials » MongoDB Tutorial » Indexes in MongoDB

Indexes in MongoDB

Introduction to Indexes in MongoDB

Indexing in MongoDB Database is important and is responsible for making database efficient, MongoDB has its ways of implementing indexing and offers various types. In MongoDB, we use create Index function to create an index and dropIndex function to drop the index. Before indexing on any new collection with a specific field, we have to understand that MongoDB already implements indexing on “_id” by default. Creating an index on “_id” by default happens every time we create a new collection. This happens to block the user from inserting more than one document with a similar value for the filed of _id. Indexing helps improve the speed of search operations as the searching is carried upon indexes that carry few fields instead of traditionally searching the whole documents. The default index created on the creation of the collection “_id” cannot be dropped.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Now that we have understood what Indexing in MongoDB is let’s understand the standard syntax for Index.

db.collection_name.createIndex( { fieldname: 1 or -1 } )

Interpreting the above-provided syntax, it starts as usual as with db.collection_name, followed by the function we intend to use. Here we have implemented createIndex function, with simply adding a field name we define which field we want to use. The following number, which could be 1 or -1, denotes that we need ascending or descending order.

How to Create Indexes in MongoDB?

Let us now execute the query to create an index in MongoDB and see how it works. I have a DB name test and few collections within. We will implement indexing on one of the collections, which is zips. For indexing zips, the query will be:

db.zips.createIndex({city:1})

Here, zips are the collection name, while createIndex is the function which we will use to create indexes. With “city” as our fieldname, we have passed it to be ascending order. For better working, refer the below-attached screenshot:

Indexes in MongoDB Example 1

Code Interpretation

Like explained earlier, createIndex is used to create indexes. While here, we are indexing the zips collection. Our query is db.zips.createIndex( { city:1 } ). which will result in creating indexes in the zips collection to the field name city, and with 1, we have defined it to be ascending,

Popular Course in this category
MongoDB Training Program (4 Courses, 2 Projects)4 Online Courses | 2 Hands-on Projects | 22+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,096 ratings)
Course Price

View Course

Related Courses
Oracle Training (14 Courses, 8+ Projects)All in One Data Science Bundle (360+ Courses, 50+ projects)SQL Training Program (7 Courses, 8+ Projects)Oracle DBA Database Management System Training (2 Courses)MS SQL Training (13 Courses, 11+ Projects)

Types of Indexes in MongoDB

In MongoDB, the indexing is supported for a few types, and every type carries different purposes. Following are the types of indexes supported:

1. Compound Index: This is a user-defined index supported in MongoDB where multiple fields can be indexed. To create a compound index, the query is db.collection.createIndex( { <fieldname1: 1/-1, fieldname2: 1/-1, … }). Here, the compound index query is similar to a normal index query but with multiple fields.

2. Single Field Index: Simple user-defined index with a single field. This is the normal indexing as we have seen earlier in the below example.

Query:

db.zips.createIndex({city:1})

Output:

Indexes in MongoDB Example 2

3. MultiKey Indexing: Now this is one indexing that works on values stored in an array. Here, for each element in an array, MongoDB creates an index.

Query: 

db.test.createIndex( {grade:1} )

Output:

Indexes in MongoDB Example 3

One of the advantages of these multi-key indexing is the efficiency in queries against these array fields. And this indexing can be implemented on arrays with nested documents and arrays containing scalar variables.

4. Text Indexing: For the purpose of searching the string content or an array of string, ina collection, indexing over the test is supported in MongoDB.

5. Hashed Index: Using the hashes of the indexed fields’ values, Hashed Indexing in MongoDB is achieved. MongoDB also supports sharding based on the hash. The aim is to reduce the size of the index. Range queries are not supported here.

Query: 

db.collectionname.createIndex( { name: "hashed" } )

Output:

Indexes in MongoDB Example 4

How to Drop Indexes in MongoDB?

Now, that we have understood and learned what indexing in MongoDB is and how it’s done, let us understand how to drop an index. Just like creating a new index, dropping an index has its advantages.

Query:

db.collection_name.dropIndex()

The above dropIndex method is used to remove or drop a particular index in the MongoDB collection. We have to specify an index to drop here.

One important thing to remember is that an index created up the field name “_id”, cannot be deleted; it is the default.

Examples:

We have a collection name zips, where we will implement methods to create and drop the index. We will first check a single document and its structure and then implement an index for the state field.

Query:

db.zips.find().limit(1)
db.zips.createIndex ({state:-1})

Output:

Zips Example 5

Now that we have learned and implemented the methods to create an index let us learn how to check for present indexes in a collection. In MongoDB, we have a special method for fetching available indexes, and it is “getIndexes”, which returns all the indexes present in a collection.

Query: 

db.zips.getIndexes()

This query will return a document in the form of an array, which holds details for the collection.

Output:

Array Example 6

As you can see, we have a total of three indexes, out of which the first index is of _id, which is the default index. Then we have our simple index created on the city field, which is in ascending order. And the last index is our lately created index on the state field, and it is in descending order. In the above output, we have a document which holds the details of the indexes, where “v” is the version of the index format, then the key is the name of the field and order we used. Then we have the name of the index, which consists of the field’s name followed by order of the index. And lastly, we have the “ns” which is the name-space for the index.

Conclusion

To conclude, we understood that Indexing is important to smoothen the tasks. MongoDB implemented indexes using db.collectionname.createIndex() and for every new collection created, a default index is created with “_id” and this index cannot be deleted. We learned about multiple types of indexes that can be created. Finally, we understood how to drop these indexes.

Recommended Article

This is a guide to Indexes in MongoDB. Here we discuss how to Create & Drop Indexes in MongoDB and its different types along with its examples. You can also go through our other suggested articles to learn more –

  1. How Does Collection Method Works in MongoDB?
  2. MongoDB Alternatives | Top 8
  3. Introduction to MongoDB Tools
  4. Lookup in MongoDB With Characteristics
  5. MongoDB Limit() | How to Works?
  6. Guide to MongoDB Administration

MongoDB Training Program (4 Courses, 2 Projects)

4 Online Courses

2 Hands-on Projects

22+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
MongoDB Tutorial
  • Advanced
    • MongoDB Array
    • PostgreSQL ARRAY_AGG()
    • Indexes in MongoDB
    • MongoDB create Index
    • MongoDB Collection
    • MongoDB List Collections
    • MongoDB Capped Collections
    • MongoDB Auto Increment
    • MongoDB Projection
    • Replication in MongoDB
    • Mongo DB Create Database
    • MongoDB Compass
    • MongoDB Users
    • MongoDB Authentication
    • MongoDB GridFS
    • MongoDB Relationships
    • MongoDB Monitoring
    • Backup in MongoDB
    • MongoDB Sharding
    • MongoDB Java Drivers
    • MongoDB Import
    • Mongo Database Interview Questions
  • Basics
    • What is MongoDB
    • How To Install MongoDB
    • MongoDB Tools
    • MongoDB GUI Tools
    • MongoDB Versions
    • MongoDB Commands
    • Advantages of MongoDB
    • MongoDB Features
    • Is MongoDB NoSQL
    • Is MongoDB Open Source
    • Build Web Applications using MongoDB
    • MongoDB vs Elasticsearch
    • MariaDB vs MongoDB
    • Firebase vs MongoDB
  • Commands
    • MongoDB Limit()
    • MongoDB count
    • MongoDB Aggregate
    • MongoDB Distinct
    • MongoDB Unique
    • MongoDB find
    • MongoDB insert
    • MongoDB Delete
    • MongoDB Update
    • Lookup in MongoDB
    • order by in MongoDB
    • MongoDB $regex
    • MongoDB $elemMatch
    • MongoDB ObjectId()
    • MongoDB Skip()
    • MongoDB Date Query
    • MongoDB Timestamp
    • MongoDB sort()
    • MongoDB group by
    • MongoDB Join

Related Courses

MongoDB Certification Course

Oracle Certification Course

All in One Data Science Course

SQL Training Course

Oracle DBA Course

MS SQL Certification Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - MongoDB Training Program (4 Courses, 2 Projects) Learn More