How do I list all databases for a connection using Mongo C# Driver?
The db command displays the name of the current database. To switch to a different database, type the use command and specify that database.
Which of the following also returns a list of databases? Explanation: show databases is new in version 2.4. Explanation: The mongo shell will return the list of the collections in the current database.
Fetch all data from the collection If we want to fetch all documents from the collection the following mongodb command can be used : >db. userdetails. find(); or >db.
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
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With