37 lines
1.7 KiB
C#
37 lines
1.7 KiB
C#
using MongoDB.Driver;
|
|
using MongoDB.Driver.Linq;
|
|
using MongoDbGenericRepository.Models;
|
|
using System;
|
|
using System.Linq;
|
|
using System.Linq.Expressions;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace MongoDbGenericRepository
|
|
{
|
|
/// <summary>
|
|
/// The base Repository, it is meant to be inherited from by your custom custom MongoRepository implementation.
|
|
/// Its constructor must be given a connection string and a database name.
|
|
/// </summary>
|
|
public abstract partial class BaseMongoRepository : ReadOnlyMongoRepository, IBaseMongoRepository
|
|
{
|
|
/// <summary>
|
|
/// Sums the values of a selected field for a given filtered collection of documents.
|
|
/// </summary>
|
|
/// <typeparam name="TDocument">The type representing a Document.</typeparam>
|
|
/// <param name="filter">A LINQ expression filter.</param>
|
|
/// <param name="selector">The field you want to sum.</param>
|
|
/// <param name="partitionKey">The partition key of your document, if any.</param>
|
|
public virtual async Task<decimal> SumByAsync<TDocument>(Expression<Func<TDocument, bool>> filter,
|
|
Expression<Func<TDocument, decimal>> selector,
|
|
string partitionKey = null)
|
|
where TDocument : IDocument
|
|
{
|
|
var collection = string.IsNullOrEmpty(partitionKey) ? GetCollection<TDocument>() : GetCollection<TDocument>(partitionKey);
|
|
|
|
return await collection.AsQueryable()
|
|
.Where(filter)
|
|
.SumAsync(selector);
|
|
}
|
|
|
|
}
|
|
} |