У меня есть документ команды, который выглядит примерно так:
_id: ...,
name: ...,
scheduleId: ...
, и у меня есть документ игры, который выглядит примерно так:
_id: ...,
scheduleId: ...,
homeTeam: {
teamId: ...
},
awayTeam: {
teamId: ...}
Я хочу выполнить mongodbагрегация, чтобы итоговый документ после агрегирования выглядел следующим образом:
id: (Where this is the teamId of the original input document),
name: (name of the team from the input document),
schedule: [
{
id: (objectId equivalent to scheduleId's referenced in team and games documents.
homeTeam: {
id: (objectId of home team),
name: (name of home team),
goals: ...,
assists: ...,
saves: ...,
score: ...,
winner: ...,
},
awayTeam: {
id: (objectId of away team),
name: (name of home team),
goals: ...,
assists: ...,
saves: ...,
score: ...,
winner: ...,
}
}
Вот мой существующий код (он выводит массив игр с идентификаторами для каждой домашней команды и команды гостей, но не включает в себя имя изсоответствующий документ команды. Я не могу понять, как выполнить поиск идентификаторов во вложенном объекте, чтобы собрать имя каждой команды и сохранить его в соответствующем объекте homeTeam / awayTeam).
Team.withUserInfo({
$match: {
_id: mongoose.Types.ObjectId(req.params.teamId)
}})
return model.aggregate([
query,
{
$lookup: {
from: "users",
localField: "captainId",
foreignField: "_id",
as: "captain"
}
},
{
$unwind: {
path: "$captain"
}
},
{
$lookup: {
from: "users",
localField: "playerIds",
foreignField: "_id",
as: "players"
}
},
{
$lookup: {
from: "circuits",
localField: "circuitId",
foreignField: "_id",
as: "circuit"
}
},
{
$unwind: {
path: "$circuit"
}
},
{
$lookup: {
from: "games",
localField: "scheduleId",
foreignField: "scheduleId",
as: "games"
}
},
{
$project: {
_id: false,
id: "$_id",
active: true,
formattedName: true,
description: true,
logo: true,
highestPlayerRank: true,
circuitId: "$circuit._id",
scheduleId: true,
div: true,
maxPlayers: "$circuit.maxPlayers",
"captain.id": "$captain._id" ,
"captain.userName": true,
players: {
$map: {
input: "$players",
as: "player",
in: {
id: "$$player._id" ,
userName: "$$player.userName"
}
}
},
schedule: {
$map: {
input: "$games",
as: "game",
in: {
id: "$$game._id",
homeTeam: {
id: "$$game.homeTeam.teamId",
goals: "$$game.homeTeam.goals",
assists: "$$game.homeTeam.assists",
saves: "$$game.homeTeam.saves",
score: "$$game.homeTeam.score",
winner: "$$game.homeTeam.winner",
},
awayTeam: {
id: "$$game.awayTeam.teamId",
goals: "$$game.awayTeam.goals",
assists: "$$game.awayTeam.assists",
saves: "$$game.awayTeam.saves",
score: "$$game.awayTeam.score",
winner: "$$game.awayTeam.winner",
},
week: "$$game.week",
date: "$$game.date"
}
}
}
}
}]);
Это похоже наотносительно простой $ lookup, но я просто не могу понять, как это сделать.Любая помощь с благодарностью!Если что-то не имеет смысла, пожалуйста, оставьте комментарий, и я отвечу.