MongoDB result set for Aggregate ()

I started with a Mongo client making some useful queries and aggretations .. but now that I want to use it in .NET / C #, I see that I can’t just run the request as a text field.

In addition, after using the Aggregation Pipeline assembly and running the collection.Aggregate () function, I get a result set, but I have no idea how to go through it.

Can someone help me here?

Here is my code:

var coll = db.GetCollection("animals"); var match = new BsonDocument { { "$match", new BsonDocument {{"category","cats"}} } }; var group = new BsonDocument{ { "$group", new BsonDocument{ {"_id", "$species"}, {"AvgWeight", new BsonDocument{{"$avg", "$weight"}}} } } }; var sort = new BsonDocument{{"$sort", new BsonDocument{{"AvgWeight", -1}}}}; var pipeline = new[] { match, group, sort }; var args = new AggregateArgs { Pipeline = pipeline }; var res = coll.Aggregate(args); foreach (var obj in res) { // WHAT TO DO HERE?? } 

Also, I have to say that I'm a bit rusty with C # / ASP.NET / MVC, so any room would be greatly appreciated for simplification.

+5
source share
1 answer

Your result is IEnumerable from BsonDocument, you can Serialize them to C # objects using BSonSerializer. And this piece of code just writes them to the console, but you can see that you 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 you have a class called Average where the property name matches the names in BSonDocument, if you want to rename that (because _Id is not so good in C # terms regarding naming conventions), you can add $ project BsonDocument to your pipeline .

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

$ sample project (add this to your pipeline just before sorting

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

Source: https://habr.com/ru/post/1207454/


All Articles