Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Getting the list of all databases?

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

like image 659
Andrey Avatar asked May 24 '11 04:05

Andrey


People also ask

Which command we should use to show database in MongoDB?

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?

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.

How do I fetch all records in MongoDB?

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.


2 Answers

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
        }
    }
}
like image 103
Rohit Mitta Avatar answered Sep 28 '22 10:09

Rohit Mitta


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.

like image 44
Earlee Avatar answered Sep 28 '22 10:09

Earlee