Blog

MongoDB Create Index

  • (4.0)
  • | 894 Ratings

How to Create MongoDB Create Index?

Indexing

Index is a tree structure in a database that provides efficient resolution of queries to search database and provide faster result. If we don’t have index, then Mongo DB will perform scan on every collection and if the documents present in a high number inside a collection it will drastically decrease the performance.

Index is a special data structure. It stores a small portion of data of a collection in a easy to traverse form. Index only stores the value specific to a field set and ordered it by the value of the field set. This helps efficient resolution of range based queries.

Mongo DB creates unique index on _id field and thus we can’t enter two documents with same _id value. Dropping index on _id is prohibited.

Interested in mastering MongoDB Course? Enroll now for FREE demo on MongoDB Training.

Create an Index

db.collection.createIndex() method is used to create an index on a collection

Syntax : db.collection.createIndex( , )

Type of Index

1. Single Field: Mongo DB supports a user-defined index in addition to the default _id field in ascending or descending order.

Collection: records
{
 "_id": ObjectId("570c04a4ad233577f97dc459"),
 "score": 1034,
 "location": { state: "NY", city: "New York" }
}
db.records.createIndex( { score: 1 } )

2. Compound Index:  User can define multiple fields to be indexed in Mongo DB.

Collection: products
{
"_id": ObjectId(...),
"item": "Banana",
"category": ["food", "produce", "grocery"],
"location": "4th Street Store",
"stock": 4,
"type": "cases"
}
db.products.createIndex( { "item": 1, "stock": 1 } )

3. Multikey Index: If index field holds an array then mongo db uses multikey index for each element in an array.

Collection: Inventory
{ _id: 5, type: "food", item: "aaa", ratings: [ 5, 8, 9 ] }
{ _id: 6, type: "food", item: "bbb", ratings: [ 5, 9 ] }
{ _id: 7, type: "food", item: "ccc", ratings: [ 9, 5, 8 ] }
{ _id: 8, type: "food", item: "ddd", ratings: [ 9, 5 ] }
{ _id: 9, type: "food", item: "eee", ratings: [ 5, 9, 5 ] }
db.inventory.createIndex( { ratings: 1 } )

4. Geospatial Index: Mongo DB uses a special 2d sphere index for geospatial coordinate data.

db.collection.createIndex( { : "2dsphere" } )

5. Text Index: Text index is used to search on strings.

db.collection.createIndex( { "$**": "text" } )

6. Hashed Index: In hashed index hash value of field is indexed and searched on operation.

db.collection.createIndex( { _id: "hashed" } )

Mongo DB uses a special hash function to compute the hash value.

Frequently Asked MongoDB Interview Questions

Dropping Index

db.collection.dropIndex() method is used to drop a specific index.

db.collection.dropIndexes() is used to drop all indexed except for the default _id index which cannot be removed.

Create an ascending order index with JS in Node.JS

var createAscendingIndex = function(db, callback) {
 // Get the users collection
 var collection = db.collection('users');
 // Create the index
 collection.createIndex(
   { firstname : 1 }, function(err, result) {
   console.log(result);
   callback(result);
 });
};

Checkout MongoDB Tutorial

Create a descending order index with JS in Node.JS

var createDescendingIndex = function(db, callback) {
 // Get the users collection
 var collection = db.collection('users');
 // Create the index
 collection.createIndex(
   { firstname : -1 }, function(err, result) {
   console.log(result);
   callback(result);
 });
};

Create a compound order index with JS in Node.JS

var createCompIndex = function(db, callback) {
 // Get the users collection
 var collection = db.collection('users');
 // Create the index
 collection.createIndex(
   { firstname : 1,lastname : -1 }, function(err, result) {
   console.log(result);
   callback(result);
 });
};
Explore MongoDB Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

Create a text index

var createTextIndex = function(db, callback) {
 // Get the documents collection
 var collection = db.collection('users');
 // Create the index
 collection.createIndex(
   { comments : "text" }, function(err, result) {
   console.log(result);
   callback(result);
 });
};

Create a hashed Index

var createHashedIndex = function(db, callback) {
 // Get the documents collection
 var collection = db.collection('users');
 // Create the index
 collection.createIndex(
   { dateofbirth : "hashed" }, function(err, result) {
   console.log(result);
   callback(result);
 });
};

Checkout MongoDB Blogs