Field or property level serialization options in mongo db using c#.net

Element name

To specify an element name using attributes, write:

public class MyClass {
    [BsonElement("sp")]
    public string SomeProperty { get; set; }
}

The same result can be achieved without using attributes with the following initialization code:

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

Element order

public class MyClass {
    [BsonElement("sp", Order = 1)]
    public string SomeProperty { get; set; }
}
BsonClassMap.RegisterClassMap<MyClass>(cm => {
    cm.AutoMap();
    cm.GetMemberMap(c => c.SomeProperty).SetElementName("sp").SetOrder(1);
});

Identifying the Id field or property

public class MyClass {
    [BsonId]
    public string SomeProperty { get; set; }
}
BsonClassMap.RegisterClassMap<MyClass>(cm => {
    cm.MapIdProperty(c => c.SomeProperty);
    // mappings for other fields and properties
});

Ignoring null values

public class MyClass {
    [BsonIgnoreIfNull]
    public string SomeProperty { get; set; }
}

Or using initialization code instead of attributes:

BsonClassMap.RegisterClassMap<MyClass>(cm => {
    cm.AutoMap();
    cm.GetMemberMap(c => c.SomeProperty).SetIgnoreIfNull(true);
});