MongoDB indexing | Use indexing with MongoDB

Hello everyone, in last article introduction to mongodb indexing, I discussed with you about what is mongo indexing and how is used to fast fetch result in mongodb. In this article, I will show to how to create a mongodb index and other interesting things about mongodb indexing.

We need to use indexing when we want to increase the speed of our query.

How to create index-

Suppose this is your user's collection data

"address": {
"city": "New York",
"state": "California",
"pincode": "456"
"field": "cricket",
"name": "Anonymous"

For creating index simply use createIndex() .  run the following command in the shell-

Db.users.createIndex({“field”: 1})

After run createIndex, you can check field index by run following query -


This query will get this field index. To show this use explain() with the query and see.

You can use multiple files in the index. we need to use the compound index.


After run ensureIndex, you can check index by run following query -

db.users.find({"":"New york","address.state":"California"});

How to delete index-

run following command in the shell for delete all indexes from users collection


If you want to delete particular index, run following command


How to get index-


indexing is very useful for the query. If we don’t use an index then the query will find results within the whole collection. You can check this by explaining and see the winning plan. If the stage is collection then this query not using the index and if a stage is Ixscan then your query used an index.
One more important thing to remember is MongoDB query optimizer used the prefix for indexing mean what index is suitable for the query it will from the prefix. So ensure that your query first field is in your index first field.

I hope this article will useful for you. keep in touch with us we will tell you more interesting stuff like this. please like our facebook page and share this as much as you can.

introduction to indexing with mongoDB

simple steps for import and export Mongo database in ubuntu

How to install and use mongoDB in ubuntu

Leave a Reply

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