MongoDB Create Index Step by step using MongoShell

MongoDB Create Index

In this article, we shall see how to create indexes in MongoDB collection using CLI like Mongo Shell or UI like a compass or other UI tools. MongoDB Create Index can be achieved using CLI or UI tools like compass Indexing help searching the required documents efficiently, Here instead of the total database scan through every document, you searched through the ordered index first.

Today in this article, we will cover below aspects,

There are many advantages of indexing if uses appropriately,

  • Indexing supports the efficient execution of queries.
  • It’s the best means of controlling the database scan.
  • Let’s you control the scan of every document efficiently. Please note without indexes each and every document and will do a full scan in a collection.
  • Indexing helps to limit the number of documents it must inspect.
  • It provides the ability of a query to narrow results using the index
  • Indexes increased query performance.

MongoDB Create Index using Mongo Shell or CLI

Locate your mongo shell exe/utility

To create indexing please login to the MongoDB database using mongo shell.

Mongo Shell should be available in the installed location of your client application like Robo3T or Compass etc.

If using Mongo Compass mongo shell can be found at below location,

C:\Program Files\MongoDB\Server\4.0\bin

Example:

MongoDB Create Index
MongoDB mongoshell location

Please open the command prompt or PowerShell and login to your database using a connection string.

Command:

mongo < Connection string>

Example

>mongo mongodb+***://****:***********/thecodebuzz-*****-personal?authSource=admin&replicaSet=xxxxxxxrd-0&readPreference=primary&ssl=true

Above commands will let you login to your MongoDB database cluster.

MongoDB Create Index using MongoShell

Below is the basic commands create any index for MongoDB.

Commands

db.<Collection Name>.createIndex({'<Index name'':1})

Example :

db.Books.createIndex({'DateAdded':1})
db.CreditScore.createIndex({'CreditScore':1})
MongoDB indeexing using mongoShell
MongoDB indexing using mongoShell

Creating Compound Indexes using Mongo shell

Below is the basic commands for Creating Compound Indexes using Mongo shell

Commands

db.<Collection Name>.createIndex({'<Index name1'':1, '<Index name2'':1, '<Index name3'':1, '<Index name4'':1})

Example :

db.Books.createIndex({'DateAdded':1})
db.CreditScore.createIndex({'CreditScore':1})

Creating compound indexes are simpler. You need to combine createIndex() method using all the required indexes as required.

Example:

db.Books.createIndex({'DateAdded':1, 'DateLastUpdated':1, 'Price':1})

MongoDB ******0:PRIMARY> db.Books.createIndex({'DateAdded':1, 'DateLastUpdated':1, 'Price':1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1,
"$clusterTime" : {
"clusterTime" : Timestamp(1608843733, 2),
"signature" : {
"hash" : BinData(0,"8/K12Lu9yGV2kL58uFa5dBy7j7c="),
"keyId" : NumberLong("6871215961496616962")
}
},
"operationTime" : Timestamp(1608843733, 2)
}

Above execution shows status “ok”: 1 confirming the indexes are created successfully.

MongoDB Drop Indexes from Collection

User can drop the specified index or indexes (except the index on the _id field) from a collection using the below command.

Commands

db.<Collection Name>.dropIndex("Index name1'')

Drop multiple indexes,

db.<Collection Name>.dropIndex(["Index name1'',"Index name3'',"Index name2'')

Example :

db.Books.createIndex('DateAdded_1"})

That’s all, This was very much basics on getting started with the indexes in Mongodb.

References:

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

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