ryansin
ryansin

Reputation: 1817

MongoDB - loop through each database and run a command

My MongoDB instance have several databases of same design. I want to loop through each database and apply unique indexes to several collections in each database.

I understand how to apply the new unique index to the collection, but how do I loop through each database and run the command on each?

db.collection.createIndex (
    { email : 1 },
    { unique : true, collation : { locale : "en", strength : 2 } }
)

Upvotes: 3

Views: 2164

Answers (1)

chridam
chridam

Reputation: 103475

The general idea is to loop through the list returned from the commands

db.adminCommand('listDatabases')

or

db.getMongo().getDBNames()

Within the loop, create the db object with getDB() method and loop through each db's collection with db.getCollectionNames(), get the collection object with db.getCollection() or db[collectionName] bracket syntax and create the index, something like the following:

mongo = db.getMongo(); // or mongo = new Mongo();
mongo.getDBNames().forEach(function(dbname){
    db = mongo.getDB(dbname);
    db.getCollectionNames().forEach(function(collectionName) {
        collection = db.getCollection(collectionName); // or db[collectionMame]
        indexes = collection.getIndexes();
        print("Indexes for " + collectionName + ":");
        printjson(indexes);

        emailIdx = indexes.filter(function(idx){ return idx.key === { "email": 1 }; });
        if (emailIdx.length < 1) {
            collection.createIndex (
                { email : 1 },
                { unique : true, collation : { locale : "en", strength : 2 } }
            )
        }
    });
})

A useful Mongo shell cheat sheet can be found here.

Upvotes: 4

Related Questions