I’m having a problem where I can’t use aggregations in C# (at least, not with lambdas - obviously I could manually make BsonDocument
s) because enum values are being serialized as their int values instead of as strings. Here I have a small example to replicate the problem
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
enum Words
{
Foo, Bar
}
class MongoEntity
{
[BsonId]
public Guid _id { get; set; }
[BsonRepresentation(BsonType.String)]
public Words Word { get; set; }
}
class Summary
{
public int BarCount {get;set;}
}
class Program
{
public static void Main(string[] args)
{
var client = new MongoClient("mongodb://****:*****@localhost");
var database = client.GetDatabase("test");
database
.GetCollection<MongoEntity>("collection")
.DeleteMany(Builders<MongoEntity>.Filter.Empty);
database
.GetCollection<MongoEntity>("collection")
.InsertMany(new[]
{
new MongoEntity { _id = Guid.NewGuid(), Word = Words.Foo },
new MongoEntity { _id = Guid.NewGuid(), Word = Words.Foo },
new MongoEntity { _id = Guid.NewGuid(), Word = Words.Foo },
new MongoEntity { _id = Guid.NewGuid(), Word = Words.Foo },
new MongoEntity { _id = Guid.NewGuid(), Word = Words.Foo },
new MongoEntity { _id = Guid.NewGuid(), Word = Words.Foo },
new MongoEntity { _id = Guid.NewGuid(), Word = Words.Foo },
new MongoEntity { _id = Guid.NewGuid(), Word = Words.Bar },
new MongoEntity { _id = Guid.NewGuid(), Word = Words.Bar },
new MongoEntity { _id = Guid.NewGuid(), Word = Words.Bar },
});
var entities = database
.GetCollection<MongoEntity>("collection")
.Find<MongoEntity>(Builders<MongoEntity>.Filter.Empty)
.ToCursor()
.ToList();
var group = database
.GetCollection<MongoEntity>("collection")
.Aggregate()
.Group(
_ => 1,
data => new Summary
{
BarCount = data.Count(row => row.Word == Words.Bar)
});
var summary = group.ToCursor().First();
Console.WriteLine(string.Join(", ", entities.Select(e => e.Word)));
Console.WriteLine(group.ToString());
Console.WriteLine(summary.BarCount);
}
}
The output I get when I run this is:
Foo, Foo, Foo, Foo, Foo, Foo, Foo, Bar, Bar, Bar
aggregate([{ "$group" : { "_id" : 1, "BarCount" : { "$sum" : { "$cond" : [{ "$eq" : ["$Word", 1] }, 1, 0] } } } }])
0
I’m not sure if this is a bug in the driver or if I’m configuring something wrong. If it’s the latter, I appreciate any and all help!