MongoDB: Getting the list of all databases?

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

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

5条回答
  •  感情败类
    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

提交回复
热议问题