Databases
List databases
To get information about all databases existing in a MongoDB server, use the ListDatabases method on a MongoDB client.
MongoClient.ListDatabases()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");
}show dbs
show databases{
"name": "admin",
"sizeOnDisk": 40960.0,
"empty": false
}
{
"name": "config",
"sizeOnDisk": 61440.0,
"empty": false
}
{
"name": "local",
"sizeOnDisk": 73728.0,
"empty": false
}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.
An example of common filter would be to search all databases that exceeded a certain size on disk. The following query does exactly this.
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.
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