mongodb obtaining collection names c#
This is how I have solved this problem, because the accepted answer hasn't worked for me.
MongoDb version 3.4.0.
C# Driver version 2.4.3.23.
public List<string> GetCollections()
{
List<string> collections = new List<string>();
foreach (BsonDocument collection in _database.ListCollectionsAsync().Result.ToListAsync<BsonDocument>().Result)
{
string name = collection["name"].AsString;
collections.Add(name);
}
return collections;
}
MongoDB version 2.6
mongodb-csharp driver: 2.1.1
Try :
//user: root pwd:pwd dbName:admin
try
{
var client = new MongoClient("mongodb://root:pwd@localhost/admin");
var db = client.GetDatabase("admin");
foreach (var item in db.ListCollectionsAsync().Result.ToListAsync<BsonDocument>().Result)
{
Console.WriteLine(item.ToString());
}
} catch (Exception ex)
{
throw ex;
}
Important: User 'root' must exists in the db
On cmd as admin
C:\yourMongoServer\bin>mongo.exe --port 27017
use admin
db.createUser(
{
user: "root",
pwd: "pwd",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
MongoDB version: 3.4.6, C# Driver version: 2.4.4
Working Solution:
using (IAsyncCursor<BsonDocument> dbCursor = client.ListDatabases())
{
while (dbCursor.MoveNext())
{
foreach (var dbDoc in dbCursor.Current)
{
Console.WriteLine("-----{0}-----", dbDoc["name"]);
var dbName = dbDoc["name"].ToString(); // list database name
using (IAsyncCursor<BsonDocument> collectionCursor = client.GetDatabase(dbName).ListCollections())
{
while (collectionCursor.MoveNext())
{
foreach (var collDoc in collectionCursor.Current)
{
Console.WriteLine(collDoc["name"]); // list collection name
}
}
}
}
}
}