开发者

Check if mongodb database exists?

Is there a possibility to check if a mongo database allready exists开发者_如何学JAVA?


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.


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


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


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


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

        }


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


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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜