OdeToCode IC Logo

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);