Chapter 4: Ticket: User Report

Hi,

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:

           .Group(
                  c=>c.Email,
                  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:
.Project<ReportProjection>(Builders<BsonDocument>.Projection.Include("email").Include("count"))

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:

.Project<ReportProjection>(Builders<BsonDocument>.Projection.Include("count"))

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

Regards,
Arpit

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:

.Project(Builders.Projection.Include(“email”).Include(“count”))
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

Kanika

Here is the strict typed version :face_with_raised_eyebrow:

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

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.