Connect to MongoDB in C# with Credentials

9.6k Views Asked by At

Hi I'm trying to connect to my remote MongoDB with Visual Studio 2013 in c# using the latest Official MongoDB supported driver for MongoDB. The problem I'm having is I'm unable to insert a collection or possibilly even establishing the connection.

I'm using the following code to create mongo credential (DBName, User, Password)

 mongoCredential = MongoCredential.CreateMongoCRCredential("MongoDB", 
                            "xxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxx");

Setup credentials List

 mongoClientSettings = new MongoClientSettings 
        { 
            Credentials = new[] { mongoCredential }, 
            Server = new MongoServerAddress("xx.xxx.xx.xxx", 38180)
        };

Add our mongo server credentials to our client

 mongoClient = new MongoClient(mongoClientSettings);

Then to connect:

 private void button1_Click(object sender, EventArgs e)
    {
        // Connect to database
        mongoDatabase = mongoClient.GetDatabase("MongoDB");
    }

Now I try and insert a collection:

 private void button4_Click(object sender, EventArgs e)
    {
        // Create a collection
        mongoDatabase.CreateCollectionAsync("aCollection");
    }

This method is not working for we as when I run mongo from prompt and connect to remote db with credentials then run db.stats() it returns an empty db:

 > db.stats()
 {
    "db" : "MongoDB",
    "collections" : 0,
    "objects" : 0,
    "avgObjSize" : 0,
    "dataSize" : 0,
    "storageSize" : 0,
    "numExtents" : 0,
    "indexes" : 0,
    "indexSize" : 0,
    "fileSize" : 0,
    "ok" : 1
 }
 >

MongoDB is not my thing and any help here would be much appreciated as I'm going round in circles with this?

1

There are 1 best solutions below

1
On BEST ANSWER

It's possible (likely?) that CreateCollectionAsync is throwing an exception but that you aren't observing that exception.

Like all async methods in C#, CreateCollectionAsync returns immediately, and the actual work is done asynchronously in the background.

You should "await" this method. When you use await, the calling Task is suspended until the called Task completes, at which point await either returns the result of the called Task or rethrows an exception if the called Task faulted.