Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command to reindex all mongodb collections

References to reindexing MongoDB collections are usually per collection:

db.mycollection.reIndex();

I'd like to reindex a number of collections all at once. One-by-one can get a bit tiring.

What's the appropriate command to issue reIndex(); across all collections?

like image 581
Daniel May Avatar asked Aug 29 '12 22:08

Daniel May


People also ask

What is the command to list all collections in MongoDB?

To list all collections in Mongo shell, you can use the function getCollectionNames().

Do we need to rebuild index in MongoDB?

According to MongoDB documentation: Normally, MongoDB compacts indexes during routine updates. For most users, the reIndex command 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.

How many indexes does MongoDB create by default for a new collection?

MongoDB provides two geospatial indexes known as 2d indexes and 2d sphere indexes using these indexes we can query geospatial data.


1 Answers

Slightly smaller version of Sergio's answer:

db.getCollectionNames().forEach(function(collection){db[collection].reIndex()});

There is no need to get a reference to the collection first.

like image 85
Ron Pasch Avatar answered Sep 23 '22 00:09

Ron Pasch