Abstractions For MongoDB

Tuesday, March 13, 2012

I've been working with a base class like the following to dig data out of MongoDB with the 10gen driver (install-package mongocsharpdriver).

public class MongoDatastore : IDisposable
{
    protected MongoDatastore()
    {
        _db = new Lazy<MongoDatabase>(Connect);
    }

    protected MongoDatabase DB
    {
        get { return _db.Value; }
    }

    protected MongoDatabase Connect()
    {
        var server = MongoServer.Create("mongodb://lookup your server");
        var database = server.GetDatabase("lookup your database");
        return database;
    }

    public void Dispose()
    {
        if (_db.IsValueCreated && _db.Value != null)
        {
            _db.Value.Server.Disconnect();
        }
    }

    private readonly Lazy<MongoDatabase> _db;        
}

From there I can layer on a class with properties for each collection (or even a projection of a collection).

public class MongoSession : MongoDatastore
{
    public MongoCollection<Product> Products
    {
        get { return DB.GetCollection<Product>("products"); }
    }
    ...
}

And from there I only need to install-package FluentMongo and the LINQ queries are ready to go.

var product = session.Products.AsQueryable()
                     .First(m => m.ID == _id);

Comments
gravatar Sureyya Uslu Tuesday, March 13, 2012
Hey Scott ,
thanks for the post , I am looking forward for more MongoDB videos on Pluralsight.

gravatar Jake Scott Tuesday, March 13, 2012
You could also add something like this:

public static MongoCollection<T> GetCollection<T>(this MongoDatabase database)
{
Type type = typeof(T);
return database.GetCollection<T>(type.Name.ToLower() + "s");
}
gravatar scott Tuesday, March 13, 2012
@Jake: Good one.
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!