How we can create an Index on MongoDB?

廉价感情. 提交于 2019-12-18 16:47:38

问题


I want to create Index on Mongo database for performance prespective, so could you please help me how I can do it?

Your help will be appreciated here.


回答1:


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.



回答2:


The basic syntax is:

db.collection.createIndex(keys, options)

So, for example:

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

See MongoDB Indexes for the full details.



来源:https://stackoverflow.com/questions/50301130/how-we-can-create-an-index-on-mongodb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!