Chapter 4: Ticket: User Report - MostActiveCommentersAsync()

I am having problems with the syntax of this ticket.

I have done the group, short and limit but when I am going for projection, I am getting error.
I have created one projection variable for ReportProjection and then when I am passing that variable into the .Project () metod then I am getting the errors.

I am using the syntax mentioned below.

var projection = Builders.Projection
.Include(m => m.Count)
.Exclude(m => m.Id);

result = await _commentsCollection
.WithReadConcern(ReadConcern.Majority)
.Aggregate()
.Group(new BsonDocument
{
{ “_id”, “$email” },
{“count”, new BsonDocument("$sum", 1)}
})
.Sort(new BsonDocument { { “count”, -1 } })
.Limit(20)
.Project(projection) //here I am getting the issue.
.ToListAsync();

Your code looks right to me. I changed a little bit of projection variable and I am able to run:

var projection = Builders<BsonDocument>.Projection
                    .Include("count")
                    .Exclude("_id");

Kanika

Thanks Kanika.

Now the code is not throwing any error but I am not getting the exact result. I should get 331 but I am getting 0. Can you please check my code once and tell me what I am doing wrong.

          List<ReportProjection> result = null;
            
            var projection = Builders<BsonDocument>.Projection
                .Include("Count");
                //.Exclude("ID");


            result = await _commentsCollection
              .WithReadConcern(ReadConcern.Majority)
              .Aggregate()
              .Group(new BsonDocument
                {
                    { "_id", "$email" },
                    {"count", new BsonDocument("$sum", 1)}
                })
              .Sort(new BsonDocument { { "count", -1 } })
              .Limit(20)
              .Project<ReportProjection>(projection)
              .ToListAsync();

            return new TopCommentsProjection(result);
1 Like

For future reference, if someone else checks this thread.

The reason why the query does not produce desired result is because in the Group method you have created the newly count field with lower case - “count”

However when the projection is including the field count - it is pascal cased - “Count”

2 Likes