Search code examples
mongodbgroovymongorestore

Can I run mongorestore command inside a groovy file?


I have a groovy script which drops a db and restores the db from an existing backup (SQL)

Sql sql = Sql.newInstance(dbSQLUrl, userName, password) 

I passed all the required parameters and ran sql.execute() as below,

sql.execute(
        alter database dbName
        set offline with rollback immediate
        drop database dbName
       )


sql.execute(
    RESTORE DATABASE dbName
    FROM disk = 'C:\Backups'
    WITH REPLACE
)

All the above code works perfectly fine. I need to implement this for MongoDB as well. Is there an equivalent to sql.execute() in Mongo where I can run Mongo command like mongorestore in groovy file.

For Mongo I have the following code:

List credentials = []
List servers = []

credentials.push(MongoCredential.createCredential(mongoUserName, mongoDBName, mongoPassword as char[]))
servers.push(new ServerAddress(mongoHost, mongoPort))

GMongoClient mongoClient = new GMongoClient(servers,credentials)
DB mongoDB = mongoClient.getDB(mongoDBName)
mongoDB.dropDatabase()

Now I need to run/include the following command inside my groovy file, mongorestore ~/backups/first_backup/

Is there any way I can achieve this?


Solution

  • Not sure this is the most efficient way to do what you need, but you can call that command and wait for it to finish by adding this to your code:

    String command = "mongorestore ${System.properties['user.home']}/backups/first_backup"
    Process p = command.execute()
    p.waitFor()