Skip to content
dannycoates edited this page Sep 13, 2010 · 10 revisions

Building

The MongoDB.sln requires Visual Studio 2010 Beta 2, available on msdn. The driver library is named MongoDB.dll and has no other dependencies.

Basic Usage

using System;
using MongoDB;   // mongo-clr4-driver
namespace MongoSample
{
  class Program
  {
    static void Main(string[] args)
    {
      var mongo = new Mongo();
      foreach (var db in mongo.GetDatabaseNames())
      {
        Console.WriteLine(string.Format("{0}:", db));
        foreach (var col in mongo.GetDB(db).GetCollectionNames())
        {
          Console.WriteLine("\t\t" + col);
        }
      }
    }
  }
}

Working with Doc

The Doc is the document data container. It is essentially an IDictionary<string, object> with a couple Mongo specific features. In fact, you can insert any class implementing IDictionary<string, object> into a Collection but you will always get a Doc back from a collection.FindOne(). The literal syntax for dictionaries in C# makes creating Docs in code fairly clean, though not as clean as Ruby or Python.

var post = new Doc {
    {"author", "Washington Irving"},
    {"title", "On the paradox of Catch-22"},
    {"pubdate", DateTime.UtcNow},
    {"body", "lorem ipsum ..."},
    {"tags", new [] {"literature", "reviews", "random"}}
  };
mongo.blog.posts.Insert(post);

or using dynamic dispatch:

dynamic post = new Doc();
post.author = "Washington Irving";
...
post.tags = new [] {"literature", "reviews", "random"};
mongo.blog.posts.Insert(post);

Using dynamic

One cool aspect of .Net 4 is the dynamic keyword. For example, if I have a database named blog with a collection named posts, I could print the author of each post like this:

dynamic mongo = new Mongo();
foreach(var post in mongo.blog.posts.Find())
{
  Console.WriteLine(post.author);
}

Types that derive from DynamicObject

  • Mongo
    • can use m.<dbname> instead of m.GetDB("<dbname>")
  • Database
    • can use db.<collectionName> instead of db.GetCollection("<collectionName>")
  • Collection
    • can use coll.<subCollection> instead of coll.Database.GetCollection("<collectionName>.<subCollection>")
  • Doc
    • can use doc.<key> and doc.<key> = value instead of doc["<key>"] and doc["<key>"] = value

Using GridFS

GridFS support is provided in the MongoDB.GridFS namespace as an extension to the MongoDB.Collection class with full System.IO.Stream access. This example adds a new image to the images database from the local file system.

using System;
using System.IO;
using MongoDB;
using MongoDB.GridFS;
namespace MongoSample
{
  class Program
  {
    static void Main(string[] args)
    {
      var mongo = new Mongo();
      var gridfs = mongo.GetDB("images").GridFS();
      var newImage = gridfs.GetFile("summer-vacation.jpg");
      newImage.ContentType = "image/jpeg";
      using (var gridStream = newImage.Open(FileAccess.Write))
      using (var source = File.Open(@"C:\summer.jpg", FileMode.Open, FileAccess.Read))
      {
        source.CopyTo(gridStream);
      }
    }
  }
}

Unfortunately, extension methods don’t work with the dynamic keyword, so when using GridFS extensions remember to use static types.

Using the DLR

see IronPython