Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 969
sandy Avatar asked Nov 16 '15 21:11

sandy


People also ask

What is a collection in MongoDB?

It is similar to tables in Mysql to store the records. MongoDB is a schema-less database so it can store any number of fields to the documents. Users can create n number of documents into the collection, or it can be changed at any time and no need to make changes in the MongoDB database.

What is the use of MongoDB?

MongoDB is a schema-less database so it can store any number of fields to the documents. Users can create n number of documents into the collection, or it can be changed at any time and no need to make changes in the MongoDB database.

What is a capped collection in MongoDB?

A Capped collection in MongoDB is a special fixed-size collection where when its allocated sized is filled, the oldest documents inserted are automatically removed to make room for the new ones.

Can I rename a sharded or unsharded collection in MongoDB?

When renaming a sharded or unsharded collection in a sharded cluster, the source and target collections are exclusively locked on every shard. Subsequent operations on the source and target collections must wait until the rename operation completes. For more information on locking in MongoDB, see FAQ: Concurrency.


1 Answers

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" } ]
  }
)
like image 148
Mate Avatar answered Nov 01 '22 00:11

Mate