MongoDB C#聚合-展开->通过...分组 [英] MongoDB C# Aggregation - unwind -> groupBy

查看:161
本文介绍了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#聚合-展开->通过...分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆