Search code examples
mongodbmongodb-.net-driverbson

How to have a different name for entries of a mongodb document in C#?


I'm trying to do CRUD operations on documents in MongoDB and C#. I would like to have fixed structured domain entities in C# with long meaningful property names but since the name of each property will be saved in MongoDB for each document, that's not a good idea. That's because property names will be redundantly saved in database and affect the total storage and performance.

The solution I can think of to overcome this problem, is to use different names for properties in C# than in MongoDB which means a mapping between them is needed. One elegant way of doing this is to incorporate C#'s attributes, something like this:

class Book
{
    [BsonProperty("n")]
    public string Name { get; set; }
    [BsonProperty("a")]
    public string Author { get; set; }
}

In this case documents would be saved in database like this:

{ n: "...", a: "..." }

I'm not sure if this is support in MongoDB's C# Driver or not!? I can not find it myself but I was hoping I'm looking in wrong places!


Solution

  • I found it at last.

    class Book
    {
        [BsonElement("n")]
        public string Name { get; set; }
        [BsonElement("a")]
        public string Author { get; set; }
    }
    

    And this is the page with details.