Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB GroupBy Aggregate and Count Documents C#

I have a requirement to get the count of documents based on status of customer. So I need to use aggregate function and then group by based on status. I have used following code for that but the problem is that in Result I am getting the list of documents but what I just want to have is the status and count of documents under that. Can any body please help in adjusting the query to achieve the results.

var result = collection.Aggregate()
                    .Group(
                        x => x.status,
                        g => new
                        {
                            Result = g.Select(x => new CustomerDetailsList
                            {
                                ActiveType = x.status,
                                Count = g.Count()
                            }
                             )
                        }
                    );

Thanks in advance

like image 871
Manoj Sethi Avatar asked Sep 16 '25 06:09

Manoj Sethi


1 Answers

The reason you're getting a list of documents for every key is that you're running this nested Select, all you need is:

collection.Aggregate()
          .Group(
              x => x.status,
              g => new CustomerDetailsList
              {
                  ActiveType = g.Key,
                  Count = g.Count()
              }).ToList();
like image 161
mickl Avatar answered Sep 17 '25 20:09

mickl