本文介绍了MongoDB C#聚合-展开->通过...分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有带OrderItems的对象Order. 我需要按字段ProductId(在orderItems中)对数据进行分组,并显示每个产品的总和. 此解决方案效果很好:
I have object Order with OrderItems. I need grouped the data by field ProductId (in orderItems) and show sum for each product. This solution works well:
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#中准备完整的示例. 而且此解决方案不起作用.
But I don't want use pipeline, I need prepare full sample in c#. And this solution doesn't work.
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) })感谢您的帮助,
推荐答案我找到了解决方案, 我准备了额外的课程:
I found solution, I've prepared extra class:
[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;更多推荐
MongoDB C#聚合
发布评论