use ConventionPack in aggregate same as find
for example :We want save string value of Enum to database,we set EnumRepresentationConvention Convention.
then we can use it in match. but in aggregate group,it dosent work:
public enum Gender { Male,Female}
public class Person
{
public int Age { get; set; }
public Gender Gender { get; set; }
}
[HttpGet("test")]
public object Test()
{
var query=db.database.GetCollection<Person>("persons").Aggregate().Group(x => x.Age,g=>new {
g.Key,
MaleCount=g.Sum(x=>x.Gender==Gender.Male?1:0),
FemaleCount = g.Sum(x => x.Gender == Gender.Female ? 1 : 0),
});
var queryString = query.ToString();
return queryString;
}
//queryString will be: aggregate([{ "$group" : { "id" : "$age", "MaleCount" : { "$sum" : { "$cond" : [{ "$eq" : ["$gender", 0] }, 1, 0] } }, "FemaleCount" : { "$sum" : { "$cond" : [{ "$eq" : ["$gender", 1] }, 1, 0] } } } }])
note:result "$eq" : ["$gender", 0],wish:$eq" : ["$gender", "Male"]
if in Find(x=>x.Gender=Gender.Male) or Aggregate().Match(x=>x.Gender=Gender.Male),it result {"gender":"Male"} as we expect
//ConventionPack follow
var pack = new ConventionPack
{
new CamelCaseElementNameConvention(),
new IgnoreExtraElementsConvention(true),
new NamedIdMemberConvention("Id","ID"),
new EnumRepresentationConvention(BsonType.String),//
new StringObjectIdIdGeneratorConventionThatWorks()
};
ConventionRegistry.Register("myconvention", pack, x => true);
BsonSerializer.RegisterSerializer(typeof(DateTime), new DateTimeSerializer(DateTimeKind.Local));