17

Is there a possibility to check if a mongo database allready exists?

1
  • 4
    what language/driver are you using? Commented Aug 13, 2011 at 14:10

11 Answers 11

18

From the shell, if you want to explicitely check that a DB exists:

db.getMongo().getDBNames().indexOf("mydb");

Will return '-1' if "mydb" does not exist.

To use this from the shell:

if [ $(mongo localhost:27017 --eval 'db.getMongo().getDBNames().indexOf("mydb")' --quiet) -lt 0 ]; then
    echo "mydb does not exist"
else
    echo "mydb exists"
fi
Sign up to request clarification or add additional context in comments.

1 Comment

Beautiful. This works perfectly in my Docker entrypoint script, which previously created a fresh DB and overwrote whatever existing data was in my volume.
16

Yes, you can get the list of existing databases. From the Java driver you could do something like this to get the database names on a mongod server running on localhost

Mongo mongo = new Mongo( "127.0.0.1", 27017 );
List<String> databaseNames = mongo.getDatabaseNames();

This is equivalent to the mongo shell "show dbs" command. I am sure similar methods exist in all of the drivers.

1 Comment

for strange reason MongoDatabase database = mongoClient.getDatabase("NAMEDB"); if (database == null) {...} database is not NULL for inexistent DB named 'NAMEDB' and if i check database.getName()); i have as result 'NAMEDB' but 'NAMEDB' do not exist.
5

For anyone who comes here because the method getDatabaseNames(); is depreciated / not available, here is the new way to get the list of existing databases:

MongoClient mongoClient = new MongoClient();
MongoCursor<String> dbsCursor = mongoClient.listDatabaseNames().iterator();
while(dbsCursor.hasNext()) {
    System.out.println(dbsCursor.next());
}

Here is a method that validates if the database is found:

public Boolean databaseFound(String databaseName){
    MongoClient mongoClient = new MongoClient(); //Maybe replace it with an already existing client
    MongoCursor<String> dbsCursor = mongoClient.listDatabaseNames().iterator();
    while(dbsCursor.hasNext()) {
        if(dbsCursor.next().equals(databaseName))
            return true;
    }
    return false;
}

2 Comments

To any moderator: This version of the answer is directly tailored to the question.
2

in python using Pymongo

from pymongo import MongoClient

db_name = "foo"
conn = MongoClient('mongodb://localhost,localhost:27017')
db = self.conn[str(db_name)]
if bool(db_name in conn.database_names()):
   collection.drop()

Comments

2

using MongoDb c# Driver 2.4

    private bool DatabaseExists(string database)
    {
       // _client is IMongoClient
        var dbList = _client.ListDatabases().ToList().Select(db => db.GetValue("name").AsString);
        return dbList.Contains(database);
    }

usage:

        if (!DatabaseExists("FooDb")
        {
            // create and seed db

        }

Comments

1

I'd like to add a C# version. I'm using the MongoDB.Driver 2.2.2.

static bool DatabaseExists(string connectionString)
{
    var mongoUri = new MongoUrl(connectionString);
    var client = new MongoClient(mongoUri);

    var dbList = Enumerate(client.ListDatabases()).Select(db => db.GetValue("name").AsString);
    return dbList.Contains(mongoUri.DatabaseName);
}

static IEnumerable<BsonDocument> Enumerate(IAsyncCursor<BsonDocument> docs)
{
    while (docs.MoveNext())
    {
        foreach (var item in docs.Current)
        {
            yield return item;
        }
    }
}

Comments

0

Try this, it worked for me (on Mac OSx)

MongoClient mongoClient = new MongoClient("localhost");
/** **/
boolean dbExist =
    mongoClient.listDatabaseNames().
    into(new ArrayList<String>()).contains("TEST");

System.out.print(dbExist);

Comments

0

The PyMongo example above didn't work for me, so I rewrote it using the more standard list_databases() method to the MongoClient library:

from pymongo import MongoClient db_name = "foo" conn = MongoClient('mongodb://localhost,localhost:27017') if bool(db_name in conn.list_databases()): print true # or return true here else: print false # or return false here

Comments

0

In my case, I could not use listDatabaseNames, because my user did not have the rights to call this function. Instead, I just assume that it exists and call a method on this database, which will fail if it does not exist or if rights are missing.

Demo C# code:

/// <summary>
/// Tests the connection to the MongoDB server, and if the database already exists.
/// If not or an error is detected, an exception is thrown.
/// </summary>
public static void TestConnection(string mongoUrl, string mongoDatabase) {
   var client = new MongoClient(mongoUrl);
   var database = client.GetDatabase(mongoDatabase);
   try {
      // Try to perform an action on this database; will fail if it does not exist
      database.ListCollections(); 
   }
   catch {
      throw new Exception("Connection established, " +
         "but database does not exist (or missing rights): " + mongoDatabase);
   }    
}

Comments

0

I searched for how to list database names in golang and accidentially found this page. Looks like no one has provided ways to check if specific database name exists.

Assume that you are using MongoDB Go Driver, here is an approach

// client type is *mongo.Client
dbNames, err := client.ListDatabaseNames(context.Background(), bson.D{{Key: "name", Value: "YOUR-DB-NAME"}})

"dbNames" contains list of all databases in mongo server. Second parameter is a filter, in this case, it only allows database with name == "YOUR-DB-NAME". Thus, dbNames will be empty if "YOUR-DB-NAME" is not exist.

Comments

0

If you are using mongoose you can do this.

export async function verifyDBExists(dbName: string) {
  const conn: any = await connectDB();
  if (conn.connection.readyState == 1) {
    const dbs = await conn.connection.db.admin().listDatabases();
    for (const db of dbs.databases) {
      if (db.name == dbName) return true;
    }
    return false;
  }
  return false;
}

The connectDB() function returns a connection to the database. Then, assign a list of the databases in the database to dbs. Iterate over the array and return false if it does not exist. For me, console.log(dbs) returns a list like the following:

 [{ name: 'admin', sizeOnDisk: 40960, empty: false },
 { name: 'config', sizeOnDisk: 73728, empty: false },
 { name: 'local', sizeOnDisk: 73728, empty: false }]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.