MongoDB C#聚合

编程入门 行业动态 更新时间:2024-10-27 09:47:10
本文介绍了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#聚合

本文发布于:2023-11-22 09:37:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616916.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!