CSMongo is a driver written in C# for working with a Mongo database server for the .NET languages. CSMongo works hard to bridge the dynamic abilities of Mongo with the static restrictions of C#.

CSMongo is very much beta software – Use caution with valuable data.

Here are some examples of how you can use CSMongo to work with a Mongo database.

//create a database instance
using (MongoDatabase database = new MongoDatabase(connectionString)) {
 
  //create a new document to add
  MongoDocument document = new MongoDocument(new {
    name = "Hugo",
    age = 30,
    admin = false
  });
 
  //create entire objects with anonymous types
  document += new {
    admin = true,
    website = "http://www.hugoware.net",
    settings = new {
      color = "orange",
      highlight = "yellow",
      background = "abstract.jpg"
    }
  };
 
  //remove fields entirely
  document -= "languages";
  document -= new[] { "website", "settings.highlight" };
 
  //or even attach other documents
  MongoDocument stuff = new MongoDocument(new {
    computers = new [] { 
      "Dell XPS", 
      "Sony VAIO", 
      "Macbook Pro"
      }
    });
  document += stuff;
 
  //insert the document immediately
  database.Insert("users", document);
 
}

A MongoDocument allows for a fairly dynamic experience even inside of a static language like C#. The next example shows how you can access values after loading them from the database.

//create the database instance
using (MongoDatabase database = new MongoDatabase(connectionString)) {
 
  //perform chained queries
  var document = database.Find("users")
    .EqualTo("admin", true)
    .Greater("age", 20)
    .SelectOne();
 
  //work with the properties one at a time
  int age = document.Get<int>("age"); // 30
  string color = document.Get<string>("settings.color"); // "orange"
 
  //set fallback values if missing or cannot convert
  string website = document.Get<string>("website", "missing"); // "missing"
  int missing = document.Get<int>("not.a.real.property", 4); // 4
 
  //map a document into a new anonymous type
  var user = document.Get(new {
    name = "undefined",
    age = -1,
    settings = new {
      background = "missing.jpg",
      font = "Monospace"
    }
  });
 
  //then use the values normally
  Console.WriteLine(user.settings.background); // "abstract.jpg"
 
}