Notes for creating indexes in MongoDB

  • 2020-05-13 03:44:45
  • OfStack

Last week, I posted a post "MongoDB those pits" on ruby-china, which received a very warm response. Many of the replies were insightful. One of them made in-depth mention of the indexing method of MongoDB, which led me to have a deeper understanding of the indexing method of MongoDB and some precautions.

As mentioned in MongoDB those pits, running the index build command directly in the foreground will block the entire database, so it is recommended to use background to build the index. Before version 2.6, even though secondary server was indexed using background, secondary was indexed using foreground, which caused secondary to also cause database blocking problems. Version 2.6 fixed this Bug, and after version 2.6, when using background indexing, it really moved to the background.

To minimize the impact of indexing on MongoDB Server, one method is to convert MongoDB Server to standalone mode. The specific approach is as follows:

1. First stop secondary server, restart MongoDB after canceling the --replSet parameter and changing MongoDB port, then MongoDB will enter standalone mode;

2. Run the command ensureIndex to build the index in standalone mode. It is recommended to use foreground mode.

3. Close secondary server after index establishment and start in normal mode;

4. According to steps 1 to 3 above, index secondary in turn. Finally, temporarily convert primary server to secondary server, index primary server in the same way as 1 to 3, and then convert it to primary server.

This is cumbersome, but it minimizes the impact of indexing on MongoDB, and is worth doing in some cases.


Related articles: