【问题标题】:Grouping and projection with mongodb C# driver使用 mongodb C# 驱动程序进行分组和投影
【发布时间】:2015-04-08 14:42:28
【问题描述】:

我有以下实体集合:

public class Branch
{
    [BsonId]
    public ObjectId Id { get; set; }
    public string Description { get; set; }
    public ObjectId PartnerId { get; set; }
    public IEnumerable<Discount> Discounts { get; set; }
}

我想按 PartnerId 分组并选择 PartnerId,首先不是 null 描述并连接 (SelectMany) 组中的所有 Discounts 数组。基本上想要的结果是一个数组:

public class GroupProjection
{
    public ObjectId PartnerId { get; set; }
    public string Description { get; set; }
    public IEnumerable<Discount> Discounts { get; set; }
}

是否使用 AggregateAsync API 完成?

我刚刚开始使用 mongodb 和 mongo c# 驱动程序。是否可以使用 Linq 或者我必须求助于 JScript 组定义来构建管道?

我查看了 tests 的 c# 驱动程序,但不是很明显,因为它们使用内部帮助程序来构建具有分组标准的 Bson 文档。

【问题讨论】:

    标签: c# .net linq mongodb mongodb-.net-driver


    【解决方案1】:

    MongoDB fluent API 目前不支持SelectMany 扩展方法。但是,您可以解决此问题。

    var groupResult =
        await collection
            .Aggregate()
            .Group(
                x => x.PartnerId,
                g => new
                {
                    PartnerId = g.Key,
                    Description = g.First(x => x.Description != null).Description,
                    Discounts = g.Select(x => x.Discounts)
                })
            .ToListAsync();
    
    var result =
        groupResult
            .Select(x =>
                new GroupProjection
                {
                    PartnerId = x.PartnerId,
                    Description = x.Description,
                    Discounts = x.Discounts.SelectMany(d => d)
                })
            .ToList();
    

    【讨论】:

    • 谢谢,应该不错。不过,我需要一些时间来为我的查询编写测试。
    • 在测试查询时我遇到了另一个问题,也许你可以看看。stackoverflow.com/questions/29670319/…
    • 显然,要完成这项工作,还需要分组或索引,否则第一个语句会选择错误的元素。
    猜你喜欢
    • 2016-05-15
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多