Databases

List databases

To get information about all databases existing in a MongoDB server, use the ListDatabases method on a MongoDB client.

MongoClient.ListDatabases()
AccessDatabases.cs
var client = new MongoClient(Utils.DefaultConnectionString);
var databases = await Client.ListDatabasesAsync();

// iterate databases result

while (databases.MoveNext())
{
    var currentBatch = databases.Current;
    Utils.Log(currentBatch.AsEnumerable(), "List databases");
}

In case you want to get the results instantly rather than iterating a Task<IAsyncCursor> result you can use the ToListAsyncon a IAsyncCursor method.

var databases = await Client.ListDatabases().ToListAsync();

foreach (var database in databases)
{
    Utils.Log(database);
}

Filter databases

When listing databases you can use options to filter the returned results by passing an instance of ListDatabasesOptions on the ListDatabases method.

MongoClient.ListDatabases(ListDatabases options)
AccessDatabases.cs
// Search only for the 'admin' database
// Return only the name
var adminDatabase = (await Client.ListDatabasesAsync(
    new ListDatabasesOptions
{
    Filter = Builders<BsonDocument>.Filter.Eq("name", "admin"),
    NameOnly = true
})).FirstOrDefault();

An example of common filter would be to search all databases that exceeded a certain size on disk. The following query does exactly this.

AccessDatabases.cs
// Search for all databases tha exceeded 60000 bytes
var highSizeDatabases = await Client.ListDatabases(new ListDatabasesOptions
{
    Filter = Builders<BsonDocument>.Filter.Gte("sizeOnDisk", 60000),
}).ToListAsync();

The above query won't work if you set NameOnly = true in the ListDatabasesOptions

Get a database reference

The very first thing you need to do before accessing any data in MongoDB is to get a reference to a database using the GetDatabase method on a MongoDB client.

MongoClient.GetDatabase(string databaseName)
IMongoDatabase adminDb = Client.GetDatabase("myDatabase");

IMongoDatabase interface represents a database in MongoDB and expose its settings along with several methods that can give you access to its collections or another IMongoDatabase reference with different read/write settings

Last updated