Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB result set for Aggregate()

I started out with Mongo client doing some nifty queries and aggretations.. but now that I want to use it in .NET/C#, I see that I can't simply run the query as text field..

Furthermore, after resorting to building an Aggregation Pipeline, and running the collection.Aggregate() function, I'm getting a result set, but I have no idea how to traverse it..

Can anyone help guide me here?

Here's 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 should say that I'm a little rusty with C# / ASP.NET / MVC so any room for simplification would be much appreciated.

like image 447
Eyal Zinder Avatar asked Nov 21 '14 23:11

Eyal Zinder


People also ask

What does MongoDB aggregate return?

aggregate() method returns a cursor to the documents produced by the final stage of the aggregation pipeline operation, or if you include the explain option, the document that provides details on the processing of the aggregation operation.

How do you use a set in aggregate?

You can include one or more $set stages in an aggregation operation. To add field or fields to embedded documents (including documents in arrays) use the dot notation. See example. To add an element to an existing array field with $set , use with $concatArrays .

How do I export MongoDB aggregation results?

You can use mongo shell and custom javascript to export whole document in one go, please check $match stage should honor the index. 1. Write your mongodb aggregation query in a javascript file and save it as script. js file.

What are the differences between using aggregate () and find () in MongoDB?

With aggregate + $match, you get a big monolithic BSON containing all matching documents. With find, you get a cursor to all matching documents. Then you can get each document one by one.


1 Answers

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"}, 
                        } 
                } 
            };
like image 167
Ben Croughs Avatar answered Sep 23 '22 10:09

Ben Croughs