By default, ensureIndex () is a blocking operation, and all other operations in the database are paused until the index creation is complete. However, mongodb Versions later than or equal to Version 1.3.2 provide optional options for creating indexes in the background.
To create an index in the background, add the background: true option. For example:
> Db. things. ensureIndex ({x: 1}, {background: true });
> Db. things. ensureIndex ({name: 1}, {background: true, unique: true,
... DropDups: true });
When the background mode is started, other operations, including writing, are not blocked during index creation. This index will not be applied to the query before it is created.
Although this operation is of the "background" type, it means other operations can be executed concurrently, but this command will not be returned to the shell prompt immediately before the creation is complete. To perform other operations at the same time, you can open another mongo shell instance.
Note that index creation in the background mode is a new method, which is slower than the default frontend mode: more time is required to create indexes.
During index creation, you can run the db. currentOp () command to check that this operation is still in progress (displayed as an insert operation for system. indexes ). You can use db. killOp () to terminate the creation process.
During index creation, the index is visible in system. indexes, but it is not used in the query operation before the index is created.
Note:
- Each set can only create one index at a time.
- Some management operations, such as repairDatabase, cannot be used during index creation in the background.
- (Used in the production environment) v1.4 or later.