MongoDB: Getting the list of all databases?

后端 未结 5 874
太阳男子
太阳男子 2021-01-01 22:38

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

相关标签:
5条回答
  • 2021-01-01 23:13

    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()));
    }
    
    0 讨论(0)
  • 2021-01-01 23:13

    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.

    0 讨论(0)
  • 2021-01-01 23:16

    Very easily:

    var server = MongoServer.Create("mongodb://localhost/?safe=true");
    var databaseNames = server.GetDatabaseNames();
    
    0 讨论(0)
  • 2021-01-01 23:16

    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

    0 讨论(0)
  • 2021-01-01 23:20

    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
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题