无法在MongoDB C#驱动程序中执行多个组
本文关键字:执行 驱动程序 MongoDB | 更新日期: 2023-09-27 18:35:01
我正在尝试使用 Linq 显示每个制造商每月从 MongoDB 集合中的统计信息计数。
[{
Manufacturer: '',
Statistics: [{
Month: '',
Counts: 0
}]
}]
所以我正在尝试以下 linq 查询:
var result = _statisticsRepository
.All()
.GroupBy(g => g.ManufacturerId)
.Select(s => new
{
Manufacturer = s.Key,
Statistics = s
.GroupBy(a => a.Values["DATA_MONTH"])
.Select(a => new
{
Month = a.Key,
Counts = a.Sum(d => d.Count)
})
});
当我尝试此代码时,出现此错误:
NotSupportedException: The method GroupBy is not supported in the expression tree: {document}.GroupBy(a => a.Values.get_Item("DATA_MONTH")).
我这样做的方式是错误的,还是这是我在 C# 驱动程序中的限制?还是有其他方法可以做到这一点?
可以使用聚合框架代替 LINQ 来获取所需的数据:
var group1 = new BsonDocument
{
{ "_id", new BsonDocument{{"ManufacturerId", "$ManufacturerId"},{"DATA_MONTH", "$DATA_MONTH"} }},
{ "Count", new BsonDocument
{
{
"$sum", $Count }
} }
};
var group2 = new BsonDocument
{
{ "_id", "$_id.ManufacturerId" },
{ "Statistics ", new BsonDocument { { "$addToSet",new BsonDocument{{"Month", "$_id.DATA_MONTH"},{"Count","$Count"} } } }},
};
var result = database.GetCollection<BsonDocument>("Manufacturers").Aggregate()
.Group(group1)
.Group(group2)
.ToList();