NJS NJS - 3 months ago 35
C# Question

MongoDB exception using C# Fluent Aggregation Framework

I'm trying to write a very simple grouping query, using the MongoDB fluent aggregation syntax in the C# driver.

I'm grouping documents by author and returning the count per author. I don't need to return the author names, only the counts. The following code compiles, but when I execute it, I get this exception:


Command aggregate failed: the group aggregate field name '$sum' cannot be an operator name.


var query = Collection<TestFile>()
.Aggregate()
.Group(
t => t.AuthorName,
grp => grp.Count()
)
.ToEnumerable();


MongoDB version: 3.2.4

MongoDB C# Driver version: 2.2.3.3

Answer

Try it like so (not tested yet though)

var query = Collection<TestFile>()
    .Aggregate()
    .Group(
        t => t.AuthorName,
        grp => new { Count = grp.Count() }
     )
     .ToEnumerable();