OdeToCode IC Logo

Working with MongoDB Conventions

Thursday, March 8, 2012

I  started working with Mongo again recently and needed to fiddle a bit to retrieve existing data using the official 10gen driver.

Let's say you have the following persisted in a Mongo collection:

{
    "_id": ObjectId("4efa88..."),
    "first_name": "Scott"
};

The driver will happily work with an object of the following type using the default mapping conventions.

public class Person
{
    public ObjectId _id { get; set; }
    public string first_name { get; set; }
}

Of course, the C# class doesn't follow the CLR convention of using PascalCase for property names. Fortunately, you can create custom naming conventions for the driver.

class NameConvention : IElementNameConvention
{
    public string GetElementName(MemberInfo member)
    {
        return member.Name.ToLower();
    }
}

Then register the custom convention during application startup.

var conventions = new ConventionProfile();
conventions.SetElementNameConvention(new NameConvention());

BsonClassMap.RegisterConventions(conventions,
    t => t.Namespace.StartsWith("MyApp"));

And now you can have as many capital letters as you want in the property name (and LINQ queries with FluentMongo still work).

public class Person
{
    public ObjectId _id { get; set; }
    public string First_Name { get; set; }
}