Search code examples
c#mongodbmongodb-.net-driver

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?


Solution

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