MongoDB C#聚合-展开->;groupBy
本文关键字:gt groupBy 展开 聚合 MongoDB | 更新日期: 2023-09-27 18:20:31
我有对象Order with OrderItems。我需要按字段ProductId(在orderItems中)对数据进行分组,并显示每个产品的总和。此解决方案运行良好:
var collection = database.GetCollection<Order>("Order");
var result = collection.Aggregate().Unwind(x=>x.OrderItems)
.Group(new BsonDocument
{
{"_id", "$OrderItems.ProductId"},
{"suma", new BsonDocument
{
{ "$sum" , "$OrderItems.UnitPriceExclTax"}
}
}
}).ToListAsync().Result;
但我不想使用管道,我需要在c#中准备完整的样本。这个解决方案不起作用。
var collection = database.GetCollection<Order>("Order");
var result = collection.Aggregate()
.Unwind(x=>x.OrderItems)
.Group(i => i.ProductId, g => new { ProductId = g.Key, Count = g.Sum(i.UnitPriceExclTax) })
感谢您的帮助,
我找到了解决方案,我准备了额外的课程:
[BsonIgnoreExtraElements]
public class UnwindedOrderItem
{
public OrderItem OrderItems { get; set; }
}
var agg = database.GetCollection<Order>("Order")
.Aggregate()
.Unwind<Order, UnwindedOrderItem>(x => x.OrderItems)
.Group(x=>x.OrderItems.ProductId, g => new
{
Id = g.Key,
Suma = g.Sum(x=>x.OrderItems.PriceExclTax)
})
.ToListAsync().Result;
在我看来,您正在尝试使用linq
语法而不是mongodb
。我不知道有什么解决方案可以允许类似于您在aggregation-pipeline
中描述的语法。