MongoDB: Getting the list of all databases?

大城市里の小女人 提交于 2019-12-18 15:12:45

问题


How do I list all databases for a connection using Mongo C# Driver?


回答1:


Very easily:

var server = MongoServer.Create("mongodb://localhost/?safe=true");
var databaseNames = server.GetDatabaseNames();



回答2:


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



回答3:


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



回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/6105678/mongodb-getting-the-list-of-all-databases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!