13

如何使用 Mongo C# 驱动程序列出连接的所有数据库?

4

5 回答 5

17

非常简单地:

var server = MongoServer.Create("mongodb://localhost/?safe=true");
var databaseNames = server.GetDatabaseNames();
于 2011-05-24T04:50:22.427 回答
7

MongoServer 类在 2.0.0 版中已弃用。

您可以使用 ListDatabasesAsync

using (var cursor = await client.ListDatabasesAsync())
{
    await cursor.ForEachAsync(d => Console.WriteLine(d.ToString()));
}
于 2015-11-09T09:46:56.453 回答
5

工作解决方案:

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
        }
    }
}
于 2017-08-29T11:25:10.203 回答
1

正如 Juri 指出的那样,MongoServer 类在 2.0.0 版本中已被弃用。如果您不想使用异步,我是这样做的:

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

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

就一件事。它采用 BsonDocument 格式,包含 2 个元素:“name”和“sizeOnDisk”。

希望这可以帮助。

于 2016-10-21T06:37:12.513 回答
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

于 2017-06-14T10:02:32.030 回答