首页 文章

使用mongodb C#驱动程序进行分组和投影

提问于
浏览
3

我有以下实体集合:

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#driver . 是可以使用Linq还是我必须求助于JScript组定义来构建管道?

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

1 回答

  • 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();
    

相关问题