Home > Mobile >  Getting count from aggregate function in C#
Getting count from aggregate function in C#

Time:11-09

I am quite new to MongoDB use in C#. I am trying to get the amount of Tickets (documents) that match a specific EmployeeId. I have this function in MongoDb:

db.Tickets.aggregate([
{$match: {employeeId: 3}},
{$count: "count"}
]);

(the number 3 was just an example)

this returns the following: {count: 4}, which is correct. I want to get that count number on C# in Visual Studio.

So far I have created this method in Visual Studio:

public int GetUserTicketCount(User user)
{
  int count = collectionOfTickets.Aggregate()
  .Match(x => x.employeeId == user.GetEmployeeId())
  .Count()
  .FirstOrDefault()
  .Count();           
}

From what I have searched in SO and other forums, this method should work; however I am getting an error of "AggregateCountResult does not contain a definition for Count and no accessible extension Count accepting a first argument of type AggregateCountResult could be found (are you missing a using directive or assembly reference?)".

How may I solve this, or how may I get the count result in C#? Any and all help is highly appreciated.

CodePudding user response:

Count is a property, not a method.

.Count should work. Just remove the parentheses.

See the official docs here: http://rstam.github.io/mongo-csharp-driver/2.5/apidocs/html/T_MongoDB_Driver_AggregateCountResult.htm.

  • Related