MongoDB聚合,分组和投影

问题描述 投票:0回答:1

我在MongoDB中陷入了聚合和投影的困境,

im在mongodb驱动程序中使用c#linq。

我的问题是:我在mongo中有这样的数据列表

PartnerCode BrandCode   ItemCode
PartnerA    BrandA      ItemA
PartnerA    BrandA      ItemA
PartnerA    BrandA      ItemB
PartnerB    BrandA      ItemA
PartnerB    BrandA      ItemA

而且我想转换为分组的Parner和Brand,但要有一个收集项目的列表,该列表具有记录计数和最高计数项目的序列,并且可以限制为每组x个项目

预期结果样本为:

PartnerCode BrandCode   Items
PartnerA    BrandA      [{ItemName : ItemA, Count: 2, Seq: 1}, {ItemName : ItemB, Count: 1, Seq: 2}]
PartnerB    BrandA      [{ItemName : ItemA, Count: 2, Seq: 1}]

我已经要做的是

_collection.Aggregate().Group(g => new {
                                            g.PartnerCode,
                                            g.BrandCode,
                                            g.ItemCode
                                        }, 
                                        g => new
                                        {
                                            _id = g.Key,
                                            Count = g.Count()
                                        })
                                        .SortByDescending(s => s.Count)
                                        .Limit(10)
                                        .ToListAsync();

但是它只给出x个分组的合作伙伴,品牌和商品的记录

而且我已经喜欢这样做了>]

.GetCollection().Aggregate().Group(g => new
                                           {
                                               g.PartnerCode,
                                               g.BrandCode
                                           },
                                           g => new
                                           {
                                               _id = g.Key,
                                               Items = g.Select(s => s.ItemCode)
                                           });

这使我将结果分为合作伙伴和品牌,但其中包含所有项目。并且我坚持要得到一组项目,该组项目具有最高的项目计数顺序,并限制其中的记录。

提前感谢。

我陷入了MongoDB中的聚合和投影,我在mongodb驱动程序中使用c#linq的问题。 [

是,它正在返回其中的所有项目,因为您从未将结果投影到所需的输出,我可以看到分组部分很好,但是您的投影方法缺少投影项目数组
_collection.Aggregate().Group( //grouping partner => new { partner.Brand, partner.Code }, //projection the output of the group partnerGr => new { partnerGr.Key.Brand, partnerGr.Key.Code, //Projecting items array, you need to group by item here, and you will have to project to your desired output (count, item name) items = partnerGr.GroupBy(b => b.Item).Select(itemGr => new { ItemName = itemGr.Key, Count = itemGr.Count(), }) });
c# mongodb linq aggregation-framework projection
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.