如何在 C# Mongodb 强类型驱动程序中计算单个 属性 的平均值

How to calculate the average of a single property in C# Mongodb strongly typed driver

我正在使用官方 C# MongoDb 强类型驱动程序版本 2.7.0 与 MongoDB 交互。

考虑以下 class:

public class Book {

    public ObjectId Id {get; set;}

    public string AuthorId {get; set;}

    public int PublishYear {get; set;}

    public double Price {get; set;}

}

如何使用作者 ID 获取属于特定作者的图书的平均价格(双精度值)。

编辑:-

这是我目前尝试的方法

var client = new MongoClient(ConnectionString);

var database = client.GetDatabase(DatabaseName);

var books = database.GetCollection<Book>("Books");

var result = books.Aggregate().Match(b => b.AuthorId == authorId).Group<Book,double>(); //I stopped here at group

以下面的回答为例

MongoDB.Driver.Builders how to group and get average

连同您目前尝试过的方法,请尝试以下方法

var result = await books.Aggregate()
    .Match(b => b.AuthorId == authorId)
    .Group(b => b.AuthorId, g => 
        new {
            AuthorId = g.Key,
            AveragePrice = g.Average(p => p.Price)
        })
    .ToListAsync();
double average = result.Select(_ => _.AveragePrice).FirstOrDefault();