MongoDB:获取所有数据库的列表?

时间:2011-05-24 04:25:02

标签: mongodb mongodb-.net-driver

如何使用Mongo C#Driver列出连接的所有数据库?

5 个答案:

答案 0 :(得分:17)

很容易:

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

答案 1 :(得分:7)

在2.0.0版本中不推荐使用MongoServer类。

您可以使用ListDatabasesAsync

using (var cursor = await client.ListDatabasesAsync())
{
    await cursor.ForEachAsync(d => Console.WriteLine(d.ToString()));
}

答案 2 :(得分:2)

工作解决方案:

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

答案 3 :(得分:0)

Juri指出,版本2.0.0中不推荐使用MongoServer类。如果您不想使用异步,请按以下步骤操作:

var client = new MongoClient("mongodb://" + server_username + ":" + server_password + "@" + server_host + ":" +  server_port);

List<MongoDB.Bson.BsonDocument> databases = client.ListDatabases();

只有一件事。它采用BsonDocument格式,有2个元素:&#34; name&#34;和&#34; sizeOnDisk&#34;。

希望这有帮助。

答案 4 :(得分:0)

我无法验证给定数据库是否存在现有答案,所以这是我对它的看法:

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

然后像这样使用它:

// either you get the client with the DB validated or throws
_client = new MongoClient(settings.ConnectionString).AssertDbExists(_dbName);

使用: Mongo官方C#驱动程序v2.4.4