MongoDB C # 2.0 Multifunction Driver

I first tried Mongo, and I have a problem when I have:

public class A { public int ID {get;set;} . . . public List<B> Bs { get; set; } } public class B { public int ID { get; set; } . . . public List<C> Cs { get; set; } } public class C { public string Name { get; set; } public double Amount { get; set; } } 

and I want to get the top 10 Cs with the highest summed sums when I group C by name. So, for example, John Smith could be in several B within the same A and could also be in B among several different A

I can accomplish this within the Mongolian shell by doing:

 db.As.aggregate( {$unwind: "$Bs"}, {$unwind: "$Bs.Cs"}, {$group: { _id: "$Bs.Cs.Name", total: {$sum: "$Bs.Cs.Amount"}}}, {$sort: {total: -1}}, {$limit: 10} ); 

But I can't figure out how to do this in my C # application using the MongoDB 2.0 driver. Can someone point me in the right direction?

Also, I'm a SQL Server guy and am very used to using sprocs, should I put this particular aggregate in a saved javascript on the server and just call it from my C # application? If so, what do you call saved javascript with driver 2.0?

Thanks!

+6
source share
1 answer

Unfortunately, not all MongoDB queries can be written using LINQ. In any case, you can implement it through aggregation:

 var collection = database.GetCollection<A>("As"); var result = await collection .Aggregate() .Unwind(x => x.Bs) .Unwind(x => x["Bs.Cs"]) .Group(new BsonDocument {{"_id", "$Bs.Cs.Name"}, {"total", new BsonDocument("$sum", "$Bs.Cs.Amount")}}) .Sort(new BsonDocument("total", -1)) .Limit(10) .ToListAsync(); 
+4
source

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


All Articles