Ramesh Pasupuleti
Ramesh Pasupuleti

Reputation: 168

How to get list of all databases using MongodbClient class. (C# application)

I am using MongoDB driver, to communicate with Mongo database. I have a need where I need display all available databases. The library has only on method that says 'GetDatabase("dbname"). What is the way to get all dbs available in ny code.

Upvotes: 0

Views: 617

Answers (1)

Cinchoo
Cinchoo

Reputation: 6322

Here is how you can get the list of dbs

MongoClient client = new MongoClient("mongodb://localhost:27017");
List<string> dbs = new List<string>();
using (IAsyncCursor<BsonDocument> cursor = client.ListDatabases())
{
    while (cursor.MoveNext())
    {
        foreach (var doc in cursor.Current)
            dbs.Add((string)doc["name"]); // database name
    }
}

Upvotes: 1

Related Questions