如何在C#中使用Mongo的Aggregate框架在列表字段中累积项目?

问题描述

我有以下实体:

public class MyEntity {
    public string Id { get; set; }
    public string Code { get; set; }
    public decimal Amount { get; set; }
}

public class MyPageItem {
    public string Code { get; set; }
    public decimal Total { get; set; }
    public IList<string> Ids { get; set; } = new List<string>{};
}

以及以下分组:

IMongoCollection<MyEntity> myCollection = MongoClient.GetDatabase("DatabaseName").GetCollection<MyEntity>("MyEntity");
    
myCollection.Aggregate()
                .sort(new SortDeFinitionBuilder<MyEntity>().Ascending("code"))
                .Group(
                        x => x.Code,g => new MyPageItem {
                            Code = g.Select(x => x.Code).Last(),Total = g.Select(x => x.Amount).Sum(),Ids = //how to append Ids in this field?
                        }
                    )
                .ToListAsync();

我想在List<string> Ids添加所有ID。我该怎么办?

解决方法

反序列化查询时,使用IList界面会导致错误,但是您可以切换到:

public List<string> Ids { get; set; }

然后使用:

collection.Aggregate()
            .Group(
                x => x.Code,gr => new MyPageItem()
                {
                    Code = gr.Key,Total = gr.Sum(x => x.Amount),Ids = gr.Select(y => y.Id).ToList()
                }
            )

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...