Search code examples
c#mongodbmongodb-.net-driver

Is anyone able to connect to MongoDB using the new mongodb .net 2.0 client?


I installed MongoDB.Driver 2.0 from nuget published 4/2/2015. I also installed MondgoDB via chocolatey version 2.4.7. I created a test app in VS2013, as follows:

var client = new MongoClient();
var database = client.GetDatabase("foo");
var foo = database.GetCollection<BsonDocument>("bar");

From what I have read in the docs, this should be sufficient to connect to the server and create the database. When I check the mongodb via robomongo, I dont see that the database "foo" has been created.

I tried running mongodb via windows server and via command line (admin mode), with no results. I have disabled my firewall just in case that was an issue; still nothing. I have to say that as my first foray into MongoDB I would have expected this to just work.

What am I missing?


Solution

  • ... and create the database

    there is no such operation in mongodb, databases are created when you attempt to insert data into one

    What am I missing?

    You're not asking the driver to actually do anything. All operations are lazy. To have the driver connect and insert a document, thereby creating both the database and the collection, do something like this:

    var foo = database.GetCollection<Customer>("customer");
    foo.InsertOneAsync(new Customer { Name = "John Doe" }).Wait();
    

    where Customer is a class, e.g.

    public class Customer { 
      public ObjectId Id { get; set; }
      public string Name { get; set; }
    }
    

    Of course, you can also work with BsonDocuments, but that seems unnecessarily cumbersome.