MnomrAKostelAni
MnomrAKostelAni

Reputation: 456

Check if mongodb database exists?

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

Upvotes: 17

Views: 35447

Answers (11)

Gabriel Suttner
Gabriel Suttner

Reputation: 177

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 }]

Upvotes: 0

Mr. Morgan
Mr. Morgan

Reputation: 1

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.

Upvotes: 0

Andi
Andi

Reputation: 3498

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);
   }    
}

Upvotes: 0

leucos
leucos

Reputation: 18269

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

Upvotes: 18

Col_Parity
Col_Parity

Reputation: 11

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

Upvotes: 0

Domenico Monaco
Domenico Monaco

Reputation: 1236

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);

Upvotes: 0

Purusartha
Purusartha

Reputation: 1010

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

        }

Upvotes: 2

Jijie Chen
Jijie Chen

Reputation: 449

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;
        }
    }
}

Upvotes: 1

c24b
c24b

Reputation: 5552

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()

Upvotes: 2

Cydrick Trudel
Cydrick Trudel

Reputation: 10497

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;
}

Upvotes: 5

Jared
Jared

Reputation: 306

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.

Upvotes: 16

Related Questions