MongoDB get server

I am trying to connect to a server and get the database. It works fine, but VS2013 shows me a warning:

Warning 1 'MongoDB.Driver.MongoClientExtensions.GetServer (MongoDB.Driver.MongoClient)' is deprecated: 'Use the new API instead.

string connectionString = "mongodb://localhost:27017"; MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString)); MongoClient mongoClient = new MongoClient(settings); var server = mongoClient.GetServer(); var db = server.GetDatabase("bookstore"); var bookCollection = db.GetCollection<Book>("Book"); 

Can someone help me solve this? Tks for reading.

+5
source share
3 answers

The MongoServer class MongoServer deprecated in version 2.0.0 (see here ). You can call GetDatabase() directly on the MongoClient object:

 MongoClient mongoClient = new MongoClient(settings); var db = mongoClient.GetDatabase("bookstore"); 

Additional documentation on connecting to a MongoDB server, retrieving a database, etc. contained in the reference documentation.

+11
source

The sample code from @Robby works, but it does not return what your code expects; it returns interface objects. The C # driver has been updated to use Interface methods, as well as a number of asynchronous functions, so updating the code is probably a good idea.

A new way to get the database is - well, you no longer get the database. You get IMongoDatabase , which is the interface to the database. In addition, you will no longer have to work with MongoCollection (from the MongoDatabase object), when you get IMongoDatabase , you will work with IMongoCollection . Refactoring? You are betting! But it's worth it.

I would also recommend placing your default database in connection strings with Mongo URLs. That way, you can save hard-coded constants, such as the database name, from your code.

 // Get your connection string -- use the URL format as in example below: // name="MongoConnectionStr" connectionString="mongodb://localhost/bookstore" var connectionString = ConfigurationManager.ConnectionStrings["MongoConnectionStr"].ConnectionString; var mongoUrl = MongoUrl.Create(connectionString); var client = new MongoClient(connectionString); // Use the Mongo URL to avoid hard-coding the database name. var db = new MongoClient(mongoUrl).GetDatabase(mongoUrl.DatabaseName); // books below is an IMongoCollection var books = db.GetCollection<Book>("Books"); 
+1
source

I changed my code to the following:

 var mongoUrl = new MongoUrl(connectionString); var mongoClient = new MongoClient(mongoUrl); MongoServer server = new MongoServer(MongoServerSettings.FromClientSettings(mongoClient.Settings)); 
0
source

All Articles