Using Mendz.Data.MongoDB

Mendz.Data.MongoDB provides the types and classes that can allow developers to use MongoDB in their applications following the same concepts, designs and principles applied by Mendz.Data for ADO.Net compatible data access (like Dapper, for example).

Just like in Mendz.Data, the first step is to create a data context instance.

    public class TestMongoDbDataContext : MongoDbDataContextBase
    {
        protected override IMongoDatabase BuildContext()
        {
            var client = new MongoClient(
                ConnectionStringOptions.Instance["TestMongoDBClient"]);
            return client.GetDatabase(
                ConnectionStringOptions.Instance["TestMongoDBContext"]);
        }
    }

Then, you need to create POCOs. For the sake of this article, let's just say we'll use the same test POCO from the Mendz.Data sample.

public class Test
{
    public int TestID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

Note that in reality, to make this POCO compatible with MongoDB, Test class needs to be decorated with BSON attributes, or "class mapped". There are many ways to do it. I'll leave it to you to choose your preferred approach. Read through this on how to do exactly just that. If you choose to do the class map approach, I recommend creating it as a separate project/assembly. When working on a MongoDB "repository", reference both your model and class map projects/assemblies. Consider this approach as well to manage your class maps.

Then, the repository can be created. The same CRUDS interfaces already available in Mendz.Data can be implemented. For this article, we will only implement IDbDataReadable.

public class TestRepository
    : MongoDbRepositoryBase<TestMongoDbDataContext>, IDbDataReadable<Test>
{
    public TestRepository()
        : base()
    {
    }

    internal TestRepository(IMongoDbDataContext dbDataContext)
        : base(dbDataContext)
    {
    }
}

Next, it's time to implement IDbDataReadable.

    public Test Read(Test model, dynamic expansion, 
        out List<ResultInfo> returnValues)
    {
        returnValues = new List<ResultInfo>();
        var collection = DbDataContext.Context.GetCollection<Test>();
        var builder = Builders<Test>.Filter;
        var filter = builder.Eq(test => test.TestID, model.TestID);
        return collection.Find(filter).SingleOrDefault();
    }

Fine and dandy, don't you think? MongoDB, just like RDMS databases, can actually fit in pretty well to the Mendz.Data design. If you ask me, this is quite fantastic! You can have developers adept at using Mendz.Data, for example. And then you can easily re-tool the same developers to using Mendz.Data.MongoDB. Wow! I think that's exciting! What do you think?

Comments