У меня есть это агрегирование, и мне нужно показать новый объект с суммой GroupScore в одном и том же взлете каждого соревнования внутри typeGroup, это может быть новая агрегация или внутри того же самого. (EventId, HorseID и CompetitorID делают идентификатор TakeOff одинаковым для всех соревнований) Спасибо за помощь!
const takeOffs = await TakeOff.aggregate([
{
$lookup: {
from: Event.collection.name,
localField: "event",
foreignField: "_id",
as: "event",
},
},
{
$unwind: {
path: "$event",
preserveNullAndEmptyArrays: true,
},
},
{
$match: {
"event.typeGroup": mongoose.Types.ObjectId(req.params.id),
GroupPosition: {
$exists: true,
$ne: null,
},
GroupScore: {
$exists: true,
$ne: null,
},
},
},
{
$lookup: {
from: Competition.collection.name,
localField: "competition",
foreignField: "_id",
as: "competition",
},
},
{
$unwind: {
path: "$competition",
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: Competitor.collection.name,
localField: "competitor",
foreignField: "_id",
as: "competitor",
},
},
{
$unwind: {
path: "$competitor",
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: Horse.collection.name,
localField: "horse",
foreignField: "_id",
as: "horse",
},
},
{
$unwind: {
path: "$horse",
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: Category.collection.name,
localField: "competition.category",
foreignField: "_id",
as: "category",
},
},
{
$unwind: {
path: "$category",
preserveNullAndEmptyArrays: true,
},
},
{
$sort: {
"category.name": 1,
GroupPosition: 1,
},
},
{
$group: {
_id: {
competitionId: "$category.name",
eventId: "$event._id",
},
eventName: { $first: "$event.name" },
stage: { $first: "$event.stage" },
takeoffs: {
$push: {
_id: "$_id",
competitorName: "$competitor.name",
horseName: "$horse.name",
score: "$score",
GroupScore: "$GroupScore",
GroupPosition: "$GroupPosition",
},
},
},
},
{
$group: {
_id: "$_id.eventId",
eventName: { $first: "$eventName" },
stage: { $first: "$stage" },
competitions: {
$push: {
competition: "$_id.competitionId",
takeoffs: "$takeoffs",
},
},
},
},
{
$group: {
_id: "$_id.competitionId",
events: {
$push: {
_id: "$_id.event",
eventName: "$eventName",
stage: "$stage",
competitions: "$competitions",
},
},
},
},
]);