How do I list all databases for a connection using Mongo C# Driver?
The MongoServer class was deprecated in version 2.0.0.
You can use ListDatabasesAsync
using (var cursor = await client.ListDatabasesAsync())
{
await cursor.ForEachAsync(d => Console.WriteLine(d.ToString()));
}
The MongoServer class was deprecated in version 2.0.0 as Juri pointed out. If you don't want to use async, here's how I do it:
var client = new MongoClient("mongodb://" + server_username + ":" + server_password + "@" + server_host + ":" + server_port);
List<MongoDB.Bson.BsonDocument> databases = client.ListDatabases();
Just one thing. It is in BsonDocument format that has 2 elements: "name" and "sizeOnDisk".
Hope this helps.
Very easily:
var server = MongoServer.Create("mongodb://localhost/?safe=true");
var databaseNames = server.GetDatabaseNames();
I wasn't able validate if a given DB exists or not with the existing answers, so here's my take on it:
// extension method on IMongoClient
public static IMongoClient AssertDbExists(this IMongoClient client, string dbName)
{
bool dbFound = false;
using(var cursor = client.ListDatabases())
{
var databaseDocuments = cursor.ToList();
foreach (var db in databaseDocuments)
{
if (db["name"].ToString().Equals(dbName))
{
dbFound = true;
break;
}
}
}
if (!dbFound) throw new ArgumentException("Can't connect to a specific database with the information provided", nameof(MongoSettings.ConnectionString));
return client;
}
And then use it like this:
// either you get the client with the DB validated or throws
_client = new MongoClient(settings.ConnectionString).AssertDbExists(_dbName);
Using: Mongo Official C# driver v2.4.4
Working Solution:
MongoClient client = new MongoClient("mongodb://localhost:27017");
using (IAsyncCursor<BsonDocument> cursor = client.ListDatabases())
{
while (cursor.MoveNext())
{
foreach (var doc in cursor.Current)
{
Console.WriteLine(doc["name"]); // database name
}
}
}