mongodb obtaining collection names c#
19,028
Solution 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" } ]
}
)
Solution 2
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;
}
Solution 3
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
}
}
}
}
}
}
Author by
sandy
Updated on July 23, 2022Comments
-
sandy almost 2 years
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?
-
sandy over 8 yearsthis works:) I just had to use the line "db.ListCollectionsAsync().Result.ToListAsync<BsonDocument>().Result"
-
Dmitry Gusarov almost 6 yearsyou can just write ListCollections().ToList()
-
Alan Clark over 5 yearsBetter to use non-async_database.ListCollections() instead of using Result.
-
levilime about 4 years
item.ToString()
gives not only the collection Name but also metadata. @VansFannel's answer is up to date and works correctly. -
JHBonarius almost 4 yearswhy do you catch the exception just to throw it again?