EDUCBA

EDUCBA

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

MongoDB create Index

By Priya PedamkarPriya Pedamkar

Home » Data Science » Data Science Tutorials » MongoDB Tutorial » MongoDB create Index

MongoDB-create-Index

Introduction to MongoDB creates Index.

Mongo DB creates Index, Indexes in DBMS help increase the performance of queries like fetching and updating data. MongoDB is used by complex data mining, data analytics algorithms to manage, modify and arrange the data they work on. The data they deal with is humongous and require efficient handling. Imagine a collection that has hundreds of documents. To find documents that match a particular filter, MongoDB would have to match the filter against all the documents present in the collection, which is tedious and time-consuming. Instead of indexing documents(fields) will reduce the search time significantly. Indexes are data structures that are packed with partial data set within itself. The index stores the value of a particular field(s) in documents in an orderly fashion that supports operations such as comparators, equators, and range-based queries in sequential order.

Syntax to Create Index

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

db.collectionName.createIndex(<key and index type specification>, <options>)

Keys Keys is a document that contains a field value pair where the field is index key and value is the type of index.

For example, value is 1 for sorting index key in ascending order and -1 in descending order.

Options Option(s) is a document that contains a set of options that influences the creation of indexes. These options are optional.

Types of MongoDB Indexes

Here are the types of Indexes mention below:

Types of Indexes

1. Default id

Each document present in the Mongo collection contains an index default called “_id”. An object id is created while creating the document if no index values are present.

2. Single field

Indexing is performed on a single field, and sort operation is either ascending or descending as MongoDB can traverse in either direction.

Example:

db.collection.createIndex({"age":1})

3. Compound Index

MongoDB supports user-defined indexes in multiple fields. The order of the fields given in the compound index is quite significant. Sorting order takes from left to right, priority w.r.t to the first field mentioned in the compound indexes is higher to that of the next one.

Example:

db.collection.createIndex({“age”:1,”dim.h”:-1})

In this example, all the documents with age field are first sorted in ascending order and then descending order of height in dim.

4. Multikey Index

MongoDB uses Multikey Index to index data that is in an array format. While indexing, each element in the array is created a separate index, and the data is indexed based on the element(s) present in the array. MongoDB takes care if the index field has an array in it by default.

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,434 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)

5. Geospatial Index

MongoDB uses Geospatial indexing to find data based on its location. It supports two types of searching, 2D(two dimensional) and 3D(three dimensional). These indexes are used to get results within a range. The number of search results can also be limited by using limit(<Number>) function.

Example:

db.players.find({ loc:{ $near: { $geometry: { type: "high_school",sport:"basketball " age: [14, 17]} } } })

This example will find all the entries of students in high_school, play basketball, and are within the age range of 14 to 17.

6. Text Index

MongoDB provides Text indexing to support queries in string format. Text index can have any fields which consist of string elements or an array of string elements.

Example:

db.movies.find( { $text : { $search : "tom hardy" } } )

This example will find all the documents that have actor names like tom hanks, Tom Felton, Tom Hiddleston as well as Robert hardy and john hardy. MongoDB takes in the string provided for search and gives all the documents with a complete or partial search string.

7. Hashed Index

MongoDB uses a hashed index to support sharding. Hashing indexes calculates the hash value of the index fields using a hash function. It does not support multi-key indexing (array values). Hash indexes are created using createIndex function, and the value of the index field should always be ‘hashed’.

Example:

db.collection.createIndex( {<fieldname>: "hashed" } )

To find the documents with hash values, db.collection.find( { <fieldname>: Math.pow(2,63) } ) will return all the documents with hash indexes in the range 2^63.

Options for Indexing

Options for Indexing

1. Unique index

As the name suggests, unique indexes are unique in nature. MongoDB does not allow duplicate values if an index is created using the “unique” option.

To specify that an index is unique while creating the index, the following format should be used:

db.collection.createIndex( <key and index>, { unique: true } )

The unique constraints can be imposed on the compound index, multikey index, and text index as well.

2. Partial index

Partial indexes index documents of a collection based on a specific filter or expression. Since partial indexes index, only a subgroup of the collection space(memory) requirements are less, resulting in reduced performance.

Example:

db.pupils.createIndex( { name: 1},{ partialFilterExpression: {age: { $gt: 5 } } }

Filter expressions supported:

  • $gt, $gte, $lt, $lte (greater than, greater than or equal, less than and less than or equal)
  • $type operators
  • $exists : true operation
  • Equality operator ($eq)
  • Logical and, or operations

3. TTL index

TTL indexes a special kind of single key indexes that can be deleted from the MongoDB collection after a timeout or at a specific clock time. Some applications that log machine-generated data or logs that would eventually be invalid after some period of time find this very helpful.

Example:

db.log.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 10000 } )

4. Sparse index

Sparse indexes index only the documents that contain the field value of the index. It ignores all the other documents that don’t contain the field. By default, non-sparse indexes contain all the documents in the collections, with null as the value for those fields which are not present.

Example:

db.pupil.createIndex( { "age": 1 }, { sparse: true } )

The index does not index documents that do not contain the field age.

5. Case insensitive index

Case insensitive indexes are used to support queries that execute string comparisons without any respect to Case sensitivity.

Example:

db.collection.createIndex( { "key" : 1 },{ collation: <collation options>} )

Collation:

Collation document is used to specify language rules, letter case, etc., for string comparison.

Collation documents consist of the following :

MongoDB create Index

Conclusion

In conclusion, indexing is crucial for faster execution of queries and memory management.  Indexes can be created, modified according to the requirements of users and dropped when not needed.

Recommended Articles

This is a guide to MongoDB create Index. Here we discuss the introduction to MongoDB create Index along with the types of indexes and options for indexing along with the respective examples. You may also look at the following article to learn more –

  1. MongoDB Tools
  2. What is MongoDB?
  3. Advantages of MongoDB
  4. How to Works MongoDB Limit()?
  5. Examples of MongoDB MapReduce
  6. MongoDB Data Types | Examples
  7. Guide to MongoDB Geospatial

MongoDB Training Program (4 Courses, 2 Projects)

4 Online Courses

2 Hands-on Projects

22+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

1 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 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
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
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