我正在使用官方C#MongoDb强类型驱动程序版本2.7.0与MongoDB进行交互。
考虑以下课程:
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
答案 0 :(得分:3)
以下面的答案为例
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();