- Reference >
mongo
Shell Methods >- Collection Methods >
- db.collection.reIndex()
db.collection.reIndex()¶
On this page
-
db.collection.
reIndex
()¶ The
db.collection.reIndex()
drops all indexes on a collection and recreates them. This operation may be expensive for collections that have a large amount of data and/or a large number of indexes.Call this method, which takes no arguments, on a collection object. For example:
db.collection.reIndex()
Normally, MongoDB compacts indexes during routine updates. For most users, the
db.collection.reIndex()
is unnecessary. However, it may be worth running if the collection size has changed significantly or if the indexes are consuming a disproportionate amount of disk space.
Behavior¶
Note
For replica sets, db.collection.reIndex()
will not propagate from the
primary to secondaries. db.collection.reIndex()
will
only affect a single mongod
instance.
Important
db.collection.reIndex()
will rebuild indexes in the background if the index was originally specified
with this option. However, db.collection.reIndex()
will rebuild the _id
index in the foreground, which takes the database’s write lock.
Changed in version 2.6: Reindexing operations will error if the index entry for an indexed
field exceeds the Maximum Index Key Length
. Reindexing operations occur as part of
compact
and repairDatabase
commands as well
as the db.collection.reIndex()
method.
Because these operations drop all the indexes from a collection and
then recreate them sequentially, the error from the Maximum Index Key Length
prevents
these operations from rebuilding any remaining indexes for the
collection and, in the case of the repairDatabase
command,
from continuing with the remainder of the process.
See also