Get all collections from C# Code

2,129 views
Skip to first unread message

shweta maheshwari

unread,
May 17, 2016, 9:11:22 PM5/17/16
to mongodb-user
Hi everyone,

I am trying to get all the collection names from MongoDb server using C# code using db.GetCollectionNames() method. 
I have 12 collections in my database, but the above method returns an empty list.
I have verified that I am referring to the correct database.
What am I doing wrong? Or if there is an alternate way?

Thanks,
Shweta

Wan Bachtiar

unread,
May 18, 2016, 3:45:18 AM5/18/16
to mongodb-user

I am trying to get all the collection names from MongoDb server using C# code using db.GetCollectionNames() method.

What am I doing wrong? Or if there is an alternate way?

Hi Shweta,

Based on the GetCollectionNames() method, I assumed that you are using MongoDB .Net driver v1.x - currently at version v1.11.
You should be able to retrieve the collection names with a C# snippet code like below:

var client = new MongoClient("mongodb://<host>:<port>");
var server = client.GetServer();
var database = server.GetDatabase("databaseName");
foreach (var coll in database.GetCollectionNames())
{
    Console.WriteLine(coll.ToString());
}

The above snippet was tested on MongoDB v3.2, MongoDB .Net driver v1.11, .Net v4.5.2

If you are still having a trouble listing collection, could you provide:

  • MongoDB .Net driver version
  • MongoDB server version
  • Your C# snippet code to list collections.

Do you have access control enabled? 

If so, could you provide any MongoDB logs or if you are getting any error messages? perhaps you are connected using a database user that does not have the required access ?

Kind regards,

Wan.

Reply all
Reply to author
Forward
0 new messages