Chapter 4: Ticket: User Report


I have solved this ticket by using BsonDocuemnt for my group stage, however I would like to learn how I can use LINQ with type-safe code for this ticket instead. I am trying to group as:

                  g => new { _id = g.Key, count = g.Sum() }

Ofcourse this does not compile, but I am would like to know if I am very far off. If I can create my data classes and extension methods, how do I accomplish this pipeline?

Secondly, I think there is an error in the solution provided for this ticket. The project stage is written as:

This is wrong as at this stage in the pipeline, the documents have _id and count. It does not have a field called email. The code works because _id is included by default and is deserialized to the class. I think it should changed to:


And better yet, if I could do this in a typesafe way, I would like to know how.


1 Like

You can use:

.Group((Comment comment) => comment.Email, r=> new ReportProjection{Id= r.Key, Count=r.Sum(a => 1)})

Or (better)

.Group((Comment comment) => comment.Email, r=> new ReportProjection{Id= r.Key, Count=r.Count()})

I also have a question.

In the “possible implementation” code, there is:

But how it should work? The class ReportProjection does not have property email. There are Id and Count Properties.

email is a property in the collection and not from the class ReportProjection


Here is the strict typed version :face_with_raised_eyebrow:

result = await _commentsCollection
.Group(x => x.Email, value => new ReportProjection() {Id = value.Key, Count = value.Count()})
.Sort(Builders.Sort.Descending(c => c.Count))
.Project(Builders.Projection.Include(m => m.Count))