I want the sum of one property from all documents but not getting the proper value because the property datatype is nullable decimal, when the property is an integer, the appropriate sum is getting.
var data1 = mongoCollection.Group(e => e.ClientId,
g => new
{
Total1 = g.Sum(e => e.Abc.Val1),
Total2 = g.Sum(e => e.Abc.Val2),
Total3 = g.Sum(e => e.Abc.Val3),
Total4 = g.Sum(e => e.Abc.Val4),
}).ToList();
Need help.
MongoDB saves decimal values as strings when you save from .net core driver, that's why the sum is not doing because the value in MongoDB is string type.
You need to add [BsonRepresentation(BsonType.Decimal128)]
attribute to the decimal property of the c# class so that MongoDB can understand that this value is decimal during saving data.
Or you can register BsonSerializer in the startup class like below which considers all decimal properties of the class for saving as a decimal.
BsonSerializer.RegisterSerializer(typeof(decimal), new DecimalSerializer(BsonType.Decimal128));
BsonSerializer.RegisterSerializer(typeof(decimal?), new NullableSerializer<decimal>(new DecimalSerializer(BsonType.Decimal128)));