Skip to content

Instantly share code, notes, and snippets.

@david-torres
Last active July 7, 2023 16:26
Show Gist options
  • Save david-torres/8450526 to your computer and use it in GitHub Desktop.
Save david-torres/8450526 to your computer and use it in GitHub Desktop.
[mongo db_exists command] MongoDB command to check if a database exists. I use it with a puppet script to conditionally load up a database dump if one isn't detected. Useful for provisioning Vagrant. Returns with exit code zero if the database was found. #mongodb
function db_exists(db_name) {
db = db.getSiblingDB('admin');
db.runCommand('listDatabases').databases.forEach(function(db_entry){
if (db_entry.name == db_name) {
// quit with exit code zero if we found our db
quit(0);
}
});
// quit with exit code 1 if db was not found
quit(1);
}
db_exists('MY_DATABASE');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment