Daniel May
Daniel May

Reputation: 2262

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?

Upvotes: 8

Views: 13151

Answers (2)

Ron Pasch
Ron Pasch

Reputation: 231

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.

Upvotes: 22

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230561

What about this? It's still one-by-one for the database, but just one command for you.

db.getCollectionNames().forEach(function(coll_name) {
  var coll = db.getCollection(coll_name);
  coll.reIndex();
});

Upvotes: 19

Related Questions