MongoDB C# 2.0 驱动程序多重展开
MongoDB C# 2.0 Driver Multiple Unwinds
我是第一次尝试 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。因此,例如,John Smith 可以在单个 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}
);
但我不知道如何使用 MongoDB 2.0 驱动程序在我的 C# 应用程序中执行此操作。有人能给我指出正确的方向吗?
此外,我是一个 SQL 服务器人员并且非常习惯使用存储过程,我是否应该将这个特定的聚合放在服务器上的存储 javascript 中并从我的 C# 中调用它应用程序?如果是这样,您如何使用 2.0 驱动程序调用 stored 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();
我是第一次尝试 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。因此,例如,John Smith 可以在单个 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}
);
但我不知道如何使用 MongoDB 2.0 驱动程序在我的 C# 应用程序中执行此操作。有人能给我指出正确的方向吗?
此外,我是一个 SQL 服务器人员并且非常习惯使用存储过程,我是否应该将这个特定的聚合放在服务器上的存储 javascript 中并从我的 C# 中调用它应用程序?如果是这样,您如何使用 2.0 驱动程序调用 stored 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();