Reputation: 824
I try to connect to server and get database. It run properly but it VS2013 show me a warning :
Warning 1 'MongoDB.Driver.MongoClientExtensions.GetServer(MongoDB.Driver.MongoClient)' is obsolete: '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.
Upvotes: 9
Views: 16005
Reputation: 76
I changed my code to following:
var mongoUrl = new MongoUrl(connectionString);
var mongoClient = new MongoClient(mongoUrl);
MongoServer server = new MongoServer(MongoServerSettings.FromClientSettings(mongoClient.Settings));
Upvotes: 1
Reputation: 10188
The example code from @Robby works, but it doesn't return what your code is expecting; it returns Interface objects. The C# driver was updated to utilize Interface
methods, as well as a number of asynchronous functions, so updating your code is probably a good idea.
The new way to get a database is -- well, you don't get a database anymore. You get an IMongoDatabase
which is an interface to the database. Also, you should not work with MongoCollection
s anymore (from the MongoDatabase
object), when you get an IMongoDatabase
you will work with an IMongoCollection
. Refactoring? You bet! But it's worth it.
I would also recommend putting your default database in the Mongo URL formatted connection strings. That way you can keep hard-coded constants, such as the database name, out of 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");
Upvotes: 0
Reputation: 97120
The MongoServer
class was 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");
More documentation about connecting to the MongoDB server, retrieving a database, etc. can be found in the reference documentation.
Upvotes: 15