EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Data Science Data Science Tutorials MongoDB Tutorial Indexes in MongoDB
 

Indexes in MongoDB

Sulaksh More
Article bySulaksh More
EDUCBA
Reviewed byRavi Rathore

Updated February 28, 2023

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 drop Index 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.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

Syntax:

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,

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 drop Index 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. MongoDB Alternatives
  2. MongoDB Tools
  3. Lookup in MongoDB
  4. MongoDB Administration

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

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

EDUCBA

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

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

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

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

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

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - ENROLL NOW