How we can create an Index on MongoDB?

If you want to index on field email on users collection:

db.users.createIndex({"email":1}, {background:true})

Before applying indexing in mongodb collections you need to understand the following aspects of indexing:

Indexing strategy:

  • Check your application for what type of queries does it send to mongodb.
  • List down all such possible queries.
  • Based on the number of operations, type of operations define index type
  • Choose the correct type of indexes for application needs. Type can be single index, compound index, partial index, TTL index and so on
  • Do your queries involve the sort operations? Follow this guide on indexing for operations with sort.
  • The more detailed guide on indexing strategy here.

Test your indexes:

  • Once you have the list of indexes to be applied, test your indexes performance using explain.
  • Generate a sample application calls on your database and enable profiler (in dev or stag) to check how your indexes are performing.

How to index:

  • Create indexes in the background. It will make sure that the create index operation does not block the other operations.
  • Depending on your data size, if the indexes to be created on large collections, consider doing it in low traffic hours. Or in a scheduled maintenance window
  • You may need to consider building rolling index in certain use cases to minimize the impact of indexing.

Keep track of indexes you create:

  • Document your indexes. This may include when you have created those indexes, why and so on.

Measure your index usage stats in production:

  • Once you have applied these indexes in production, in a week or two check usage stas of your indexes to check whether they're really being used
  • Consider dropping the indexes if they're not used at all.

Caution:

  • Indexes add performance penalty for write operations. Design and apply indexes which are must for your application.

The basic syntax is:

db.collection.createIndex(keys, options)

So, for example:

$ db.users.createIndex({"username" : 1})

See MongoDB Indexes for the full details.