Reputation: 368
I'm trying to connect to a program coded in C# to a mongoDB. I have created a new collection and I have inserted some data . I'm using mlab as host for my dataBase.
MongoClientSettings settings = new MongoClientSettings();
settings.Server = new MongoServerAddress("ds145128.mlab.com", 45128);
MongoClient client = new MongoClient(settings);
var db = client.GetDatabase("unknowndb");
var coll = db.GetCollection<Book>("book");
Please help me, when I execute the program, it show me a error message that I can't connect to the DB?
Upvotes: 1
Views: 4238
Reputation: 368
Thanks a lot for you answers, this is how to connect with mongodb c# driver 2.0.1
static void Main(string[] args)
{
Task t = MainAsync(args);
t.Wait();
}
static async Task MainAsync(string[] args)
{
var client = new MongoClient("mongodb://localhost:27017/test");
var db = client.GetDatabase("name");
var coll = db.GetCollection<Book>("collName");}
Upvotes: 0
Reputation: 191
I connected like that
var connectionString = ConfigurationManager.ConnectionStrings[CONNECTION_STRING_NAME].ConnectionString;
var mongoUrl = new MongoUrl(connectionString);
var client = new MongoClient(mongoUrl);
var database = client.GetDatabase(mongoUrl.DatabaseName);
And my connection string like this. I connected to local mongodb. You can use MongoUrl
mongodb://[username:password@]host1[:port1][/[database][?options]]
mongodb://localhost:27017/dbtest?readPreference=primary
Upvotes: 2