Sir i want to connect a particular MongoDb database to c# application using Web.config. Please tell me how to do that. ?

55 views
Skip to first unread message

Hariom Sharma

unread,
Sep 11, 2017, 3:34:26 AM9/11/17
to mongodb-user
Sir i want to connect a particular MongoDb database to c# application using Web.config.
Please tell me how to do that.
?

Diego Gago

unread,
Sep 11, 2017, 6:22:31 PM9/11/17
to mongodb-user
You can use the mongodb c# driver, put your connection string in the <connectionStrings> section of your web.config, and then write a little snippet like this:

MongoUrl url = new MongoUrl(ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString);
var client = new MongoClient(url);
var db = client.GetDatabase(url.DatabaseName, null);
// now you can get collections from db

Regards,
Diego.

OmIndia Tech India

unread,
Sep 14, 2017, 8:25:40 AM9/14/17
to mongodb-user
Sir I am Using Same Code But Still Showing Error.
Error is -
WriteConcern detected an error 'not authorized for insert on admin.newcol'. (Response was { "connectionId" : 293, "err" : "not authorized for insert on admin.newcol", "code" : 13, "codeName" : "Unauthorized", "n" : 0, "ok" : 1.0 }).
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

MongoUrl url = new MongoUrl(ConfigurationManager.ConnectionStrings["myco"].ConnectionString);
        var client = new MongoClient(url);
        var ser = client.GetServer();
        ser.Ping();
        var ddb = ser.GetDatabase(url.DatabaseName);

        var col = ddb.GetCollection("newcol");

        var document = new BsonDocument
        {
           {"property", "10"},
        };


        col.Insert(document);
        Response.Write(col);

    }
Connection String in Web.config-

mongodb://admin:password@localhost:27017/admin

Wan Bachtiar

unread,
Sep 18, 2017, 4:21:11 AM9/18/17
to mongodb-user

Hi,

A couple of things:

  • You are writing into admin database. Please see C#: get a database to switch using a different database. 
  • You are logged in as admin user. Please ensure you have the necessary roles/auth to write into the intended database/collection. Note that userAdminAnyDatabase does not have insert action.

I would recommend to enrol in a free online course at MongoDB University to learn more about MongoDB. The next session for MongoDB C# Driver - M101N: MongoDB for .NET Developers starts on the 17th October.

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages