MongoDB - A Script to Create Indexes

Viewed 1519

New to MongoDB - at the moment I'm creating indexes directly from my web app however I want to instead have some sort of bash script I run (and more easily maintain) that can create my various text indexes for me.

Wanted to check is this possible? I'm unsure about how I would actually execute it if so - namely I have a Docker image running Docker - so do I have to bash into that then run the .sh? Or would I just specify the DB and collection in the script itself and just run it from terminal as usual?

Any pointers would be appreciated.

Thanks.

1 Answers

You can do it using java script:

var createIndexes = function(fullObj) {

        conn = new Mongo();
        db = conn.getDB(databaseName);

        getMapInd = null;
        setMapInd1 = db.testMappings.createIndex( { 'testId': 1}, {unique: true} )
    getMapInd = db.testMappings.getIndexes();

printjson("---------------------Below indexes created in Mappings collection-----------------------");
printjson(getMapInd);
};

createIndexes();
Related