не уверен, насколько эффективным будет этот конвейер, но он возвращает ожидаемый результат:
db.cars.aggregate(
[
{
"$group": {
"_id": "$model",
"cars": { "$push": { "model": "$model", "year": "$year" }}}
},
{
"$project": {
"cars": {
"$filter": {
"input": "$cars",
"as": "c",
"cond": { "$eq": [ "$$c.year", "2020" ]
}
}
},
"hasAnotherRecord": {
"$gt": [ { "$size": "$cars" }, 1 ]
},
"_id": 0
}
},
{
"$match": {
"cars": {
"$ne": null,
"$not": { "$size": 0 }
}
}
},
{
"$project": {
"model": {
"$arrayElemAt": [ "$cars.model", 0 ]
},
"year": {
"$arrayElemAt": [ "$cars.year", 0 ]
},
"_id": 0
}
}
]
)
c# тестовая программа:
using MongoDB.Entities;
using MongoDB.Entities.Core;
using System.Linq;
namespace StackOverFlow
{
public class car : Entity
{
public string year { get; set; }
public string model { get; set; }
}
public static class Program
{
private static void Main()
{
new DB("test");
new[] {
new car { model= "opel", year= "2020"},
new car { model= "renault", year= "2020"},
new car { model= "renault", year= "2019"},
new car { model= "nissan", year= "2021"}
}.Save();
var result = DB.Queryable<car>()
.GroupBy(c => c.model,
(model, cars) => new
{
model,
cars = cars.Select(c => new car
{
model = c.model,
year = c.year
})
})
.Select(x => new
{
cars = x.cars.Where(c => c.year == "2020"),
hasAnotherRecord = x.cars.Count() > 1
})
.Where(x => x.cars.Any())
.Select(x => new
{
x.cars.First().model,
x.cars.First().year
})
.ToList();
}
}
}