public static class FluentAggregationExtensions
{
public static Task<List<TNewResult>> ProjectToListAsync<TResult, TNewResult>(this IAggregateFluent<TResult> aggregate, Expression<Func<TResult, IEnumerable<TNewResult>>> field)
{
var fieldName = $"${((MemberExpression) field.Body).Member.Name}";
return aggregate
.AppendStage<BsonDocument>(new BsonDocument
{
{ "$unwind", fieldName}
})
.AppendStage<BsonDocument>(new BsonDocument
{
{
"$replaceRoot", new BsonDocument
{
{"newRoot", fieldName}
}
}
})
.As<TNewResult>()
.ToListAsync();
}
}
class Animal
{
public ObjectId Id { get; set; }
public string Name { get; set; }
}
[CollectionName("animals")]
class AnimalsEntity
{
[BsonId]
public ObjectId Id { get; set; }
public List<AnimalsEntity> Animals { get; set; }
}
Project only Id and Name for all animals of type Cat.
var animals = await Database
.GetCollection<AnimalsEntity>()
.Aggregate()
.Match(x => x.Name.Contains("Cat"))
.Project(x => new { Pets = x.Animals.Select(animal => new { _id = animal.Id, anmial.Name })})
.ProjectToListAsync(x => x.Animals);
Debug.WriteLine($"You own {animals.Count} animals.");