mongodb obtaining collection names c#

I'm trying to obtain a list of all databases and the associated list of collections for a connection using Mongo C# Driver.

foreach (string database in server.GetDatabaseNames()) { var db = client.GetDatabase(database); var col = ((MongoDatabase)db).GetCollectionNames(); //Do something } 

I'm able to obtain the list of databases but not the collection names. It doesn't get past

 ((MongoDatabase)db).GetCollectionNames(); 

What am I possibly missing?

11

4 Answers

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; } 
1

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" } ] } ) 
4

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 } } } } } } 

In MondoDB C# driver you have async method and "sync" method that return async cursors. This allow this kind of compact code:

List<string> collections = await (new MongoDB.Driver.MongoClient()) .GetDatabase("test") .ListCollectionNames() .ToListAsync(); 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like