Search code examples
c#.netmongodbmongodb-querymongodb-.net-driver

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


I am using the official C# MongoDb strongly typed driver version 2.7.0 to interact with MongoDB.

Consider the following class:

public class Book {

    public ObjectId Id {get; set;}

    public string AuthorId {get; set;}

    public int PublishYear {get; set;}

    public double Price {get; set;}

}

How to get the average of the books prices (as a double) that belong to a specific author using the author id.

Edit:-

This is what I tried so far

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

Solution

  • Referencing the following answer as an example

    MongoDB.Driver.Builders how to group and get average

    along with what you tried so far, try the following

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