Brian Var
Brian Var

Reputation: 6227

How to connect to MongoDB via the .Net driver?

I'm following this example, ClientMongo to connect a WPF application to my MongoDB database via the connection string. But I get an error on the MongoClient when I call the GetServer method. The error states that GetServer doesn't exist, although the correct using references and usings have been added.

Can anyone spot if I've missed a step in setting this up? Or is there an alternative solution to create a connection with the remote DB?

This is the code I've used to connect, similar to the example above. The user and password have been starred out for privacy:

using MongoDB.Bson;
using MongoDB.Driver;

namespace MongoDBApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string connectionString = "mongodb://<brian****>:<********123;>@ds048878.mongolab.com:48878/orders";

        public MainWindow()
        {
            InitializeComponent();

            var mongoUrl = MongoUrl.Create(connectionString);
            var server = new MongoClient(connectionString).GetServer();
            return server.GetDatabase(mongoUrl.DatabaseName);
        }
    }
}

Upvotes: 3

Views: 5731

Answers (1)

Markus Dietrich
Markus Dietrich

Reputation: 618

If you are using the 2.x Version of the C# driver, forget about the Server object. You can get your Database directly from the client:

var client = new MongoClient("<connectionString>");
return this.Client.GetDatabase("<databaseName>");

Upvotes: 1

Related Questions