I have a collection of people. I am trying to find the oldest person for each name. I am able to achieve that result using the mongoDB console command
db.People.aggregate([
{ '$sort': { 'Name': 1, 'Age': -1 } },
{
'$group': {
'_id': '$Name',
'docs': { '$push': '$$ROOT' },
}
},
{
'$project': {
'top_one': {
'$slice': ['$docs', 1]
}
}
} ])
What is the equivalent of this for the C# driver? I'm specifically having trouble with
'docs': { '$push': '$$ROOT' },
Here is my current C# query:
collection.Aggregate(aggArgs)
.SortByDescending(x => x.Age)
.Group(x => x.Name, x => new {
Name = x.First().Name,
FavoriteColor = x.First().FavoriteColor,
FavoriteFood = x.First().FavoriteFood
}).ToListAsync().Result;
It works close to what my mongo console command does, but I really don't like constructing an anonymous object. I would prefer to do Group(x => x.Name,x => x.First())
, but that throws and exceptions that "First()" is not supported. I believe part of the problem is that is that my Person type doesn't have an ID, so _id is put on the actual mongo document (automatically by mongo on insert). When it trys to go back in to the type, it can't do a direct mapping.
So, with the two versions of the query in mind, how do I get my full type back in C# without having to spell out EVERY field?