简体   繁体   English

MongoDB C#2.0驱动程序多次展开

[英]MongoDB C# 2.0 Driver Multiple Unwinds

I'm trying out Mongo for the first time and am having an issue where I have: 我是第一次尝试Mongo而且我遇到了一个问题:

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 get back the top 10 C's with the highest Summed Amounts when I group C by name. 当我按照名字分组C时,我希望以最高的累积金额返回前10名C. So for example, John Smith could be in several B's within a single A and could also be in B's among several different A's 因此,例如,约翰史密斯可以在单个A中的几个B中,也可以在几个不同的A中的B中。

I can accomplish this within in the Mongo Shell by running: 我可以通过运行以下命令在Mongo Shell中完成此操作:

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 cant figure out how to do this within my C# app using the MongoDB 2.0 driver. 但我无法弄清楚如何使用MongoDB 2.0驱动程序在我的C#应用​​程序中执行此操作。 Could somebody 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 stored javascript on the server and just call it from my C# app? 此外,我是一个SQL Server的人,我非常习惯使用sprocs,我应该把这个特定的聚合放在服务器上存储的javascript中,只是从我的C#app调用它? If so, how do you call stored javascript with the 2.0 driver? 如果是这样,你如何使用2.0驱动程序调用存储的javascript?

Thanks! 谢谢!

Unfortunately not all MongoDB queries can be written with LINQ. 遗憾的是,并非所有MongoDB查询都可以使用LINQ编写。 Anyway 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM