愚蠢的是,我同意为我们在工作中举办的梦幻一级方程式比赛建立一个网站.
我是新来Mongobd的,我被困在如何根据每个玩家 Select 的车手的累积积分来更新每个玩家的总积分.
我有两个Collection :球员和车手.播放器中的driver_selection
是一个驱动程序IDarray.如何通过汇总驱动程序集合中的driver_points
个字段来使用它来更新total_points
字段?
// Example player document from players collection
{
id: 1,
player_name: "Tom",
total_points: 0,
driver_selection: [1, 4, 44]
}
// Driver collection
{
id: 1,
driver_name: "Max Verstappen",
driver_points: 200.
}
{
id: 4,
driver_name: "Lando Norris",
driver_points: 150.
}
{
id: 44,
driver_name: "Lewis Hamilton",
driver_points: 100.
}
我try 在driver_selection
上使用$unwind
,然后使用id作为外部字段的驱动程序集合中的$lookup
.最后,我按id分组,并在$points
字段上使用$sum
.
但是,积分总是返回为0.
db.players.aggregate([
{
$unwind: "$driver_selection"
},
{
$lookup: {
"from": "drivers",
"localField": "driver_selection",
"foreignField": "id",
"as": "result"
}
},
{
$group: {
"_id": "$id",
"points": {
$sum: "$points"
}
}
}
])