MongoDB c# 2.0驱动程序多重unwind
本文关键字:unwind 驱动程序 MongoDB | 更新日期: 2023-09-27 17:53:46
我是第一次尝试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; }
}
,当我按名称对C进行分组时,我想要返回具有最高总金额的前10个C。例如,约翰·史密斯可能在一个a中处于几个B中,也可能在几个不同的a中处于B中
我可以在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}
);
但我无法弄清楚如何在我的c#应用程序中使用MongoDB 2.0驱动程序。有人能给我指个正确的方向吗?
另外,我是一个SQL Server家伙,我非常习惯使用进程,我应该把这个特定的聚合在服务器上存储的javascript,只是从我的c#应用程序调用它吗?如果是这样,如何使用2.0驱动程序调用存储的javascript ?
谢谢!
不幸的是,不是所有的MongoDB查询都可以用LINQ编写。无论如何,您可以通过聚合实现它:
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();