MongoDB result set for Aggregate() MongoDB result set for Aggregate() mongodb mongodb

MongoDB result set for Aggregate()


Your result is IEnumerable of BsonDocument, you can Serialize them to C# objects using the BSonSerializer. And this code snippet just writes them to your console, but you can see that you have typed objects

 List<Average> returnValue = new List<Average>(); returnValue.AddRange(documents.Select(x=> BsonSerializer.Deserialize<Average>(x))); foreach (var obj in returnValue) {     Console.WriteLine("Species {0}, avg weight: {1}",returnValue._Id,returnValue.AvgWeight); }

And then have a class called Average, where the property name match the names in the BSonDocument, if you want to rename then (because _Id is not so nice in c# terms concerning naming conventions), you can add a $project BsonDocument to your pipeline.

 public class Average {      public string _Id { get; set; }      public Double AvgWeight {get; set; } }

$project sample (add this in your pipeline just before sort

 var project = new BsonDocument             {                 {                     "$project",                     new BsonDocument                         {                             {"_id", 0},                             {"Species","$_id"},                            {"AvgWeight", "$AvgWeight"},                         }                 }             };