Search code examples
mongodbmongodb-.net-driver

Case insensitive property mapping


When serializing a MongoDB document to a POCO is there any way to make properties map case insensitive? For example I'd like this document:

{
    "id": "1"
    "foo": "bar"
}

to map to this class:

public MyObj
{
    public int Id {get; set;}
    public string Foo {get; set;}
}

Solution

  • To do that I think you will have 2 options.

    The first would be to write out a class map manually

    BsonClassMap.RegisterClassMap<MyClass>(cm => {
        cm.AutoMap();
        cm.GetMemberMap(c => c.Foo).SetElementName("foo");
    });
    

    The second would be to decorate your class with the following attributes

    public class MyObj
    {
        [BsonElement("id")]
        public int Id { get; set; }
        
        [BsonElement("foo")]
        public string Foo { get; set; }
    }
    

    The CSharp driver team have a good tutorial on serialization on the following link

    http://docs.mongodb.org/ecosystem/tutorial/serialize-documents-with-the-csharp-driver/

    Update

    I have just tried the following and this works for me, obviously I'm sure this is a much more simplified version of your code but taking a guess at how it might look.

    I have registered the two class maps separately and added the BsonKnownType to the base class.

    [BsonKnownTypes(typeof(GeoJSONObject))]
    public class Point
    {
        public string Coordinates { get; set; }
    }
    
    public class GeoJSONObject : Point
    {
        public string Type { get; set; }
    }
    
    static void Main(string[] args)
    {
        var cn = new MongoConnectionStringBuilder("server=localhost;database=MyTestDB;");
        var settings = MongoClientSettings.FromConnectionStringBuilder(cn);
        var client = new MongoClient(settings);
    
        BsonClassMap.RegisterClassMap<Point>(cm =>
        {
            cm.AutoMap();
            cm.GetMemberMap(c => c.Coordinates).SetElementName("coordinates");                   
        });
    
        BsonClassMap.RegisterClassMap<GeoJSONObject>(cm =>
        {
            cm.AutoMap();
            cm.GetMemberMap(c => c.Type).SetElementName("type");
        });
    
        var result = client.GetServer()
                  .GetDatabase("MyTestDB")
                  .GetCollection("MyCol")
                  .Find(Query.EQ("type", BsonValue.Create("xxxx")));
    }