AliReza Sabouri
AliReza Sabouri

Reputation: 5255

Mongodb C# driver ignore Null and Empty Lists (ToBsonDocument)

ConventionRegistry.Register("IgnoreIfDefault", 
                            new ConventionPack { new IgnoreIfDefaultConvention(true) }, 
                            _ => true);

var bsonDocument = anon.ToBsonDocument();

using IgnoreIfDefaultConvention can cause an unintended behavior due to the fact it affects all default values. For instance, values, as listed below, will not be saved:

int = 0
decimal = 0
bool = false

If I want to ignore only null values and Empty Arrays what is the best approach?

Upvotes: 1

Views: 3009

Answers (2)

Daniele Bosa
Daniele Bosa

Reputation: 1

This is the custom attribute we use to ignore empty collections:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class BsonIgnoreIfEmpty : Attribute, IBsonMemberMapAttribute
{
    public void Apply(BsonMemberMap memberMap)
    {
        // Get the member where the attribute is applied
        MemberInfo memberInfo = memberMap.MemberInfo;

        memberMap.SetShouldSerializeMethod(entity =>
        {
            // Get value of memberInfo
            var member = memberInfo switch
            {
                FieldInfo field => field.GetValue(entity),
                PropertyInfo property => property.GetValue(entity),
                _ => null
            };

            if (member is IEnumerable collection)
            {
                // Check if collection is empty
                return collection.GetEnumerator().MoveNext();
            }

            return false;
        });
    }
}

Upvotes: 0

dododo
dododo

Reputation: 4897

I didn't use it my own, but I think the answer is this convention: IgnoreIfNullConvention. Also you may configure a particular convention for a particular field:

BsonClassMap.RegisterClassMap<test>(c => c.MapField(e => e.A).SetIgnoreIfNull(ignoreIfNull: true));

or use this attribute BsonIgnoreIfNullAttribute

UPDATE: If you need more complicated convention, you can always implement a custom one: https://mongodb.github.io/mongo-csharp-driver/2.12/reference/bson/mapping/conventions/

Upvotes: 2

Related Questions