如何使用一组 ids 计算一个集合中的金额并更新另一个集合中的字段?

问题描述 投票:0回答:1

愚蠢的是,我同意为我们在工作中举办的梦幻一级方程式比赛建立一个网站。

我是 mongobd 的新手,我很困惑如何根据每个玩家选择的驱动程序的累积积分来更新每个玩家的总积分。

我有两个收藏:球员和车手。玩家中的

driver_selection
是驾驶员ID的数组。如何使用它通过对驱动程序集合中的
total_points
字段求和来更新
driver_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.
  }

我尝试在驱动程序集合中的

$unwind
上使用
driver_selection
,然后使用 id 作为外部字段的
$lookup
。最后,我按 id 分组并在
$sum
字段上使用
$points
。 然而积分总是返回为 0。

    db.players.aggregate([
    {
      $unwind: "$driver_selection"
    },
    {
      $lookup: {
        "from": "drivers",
        "localField": "driver_selection",
        "foreignField": "id",
        "as": "result"
      }
    },
    {
      $group: {
        "_id": "$id",
        "points": {
          $sum: "$points"
        }
      }
    }
  ])
mongodb mongodb-query aggregation-framework
1个回答
0
投票

您的聚合几乎是正确的。您只需使用

unwind
result
数组转换为对象即可。由于它作为数组返回,因此分组和求和过程无法按预期工作。
将它们每个转换为对象后,按
id
将它们分组并对
driver_points
字段进行求和

db.players.aggregate([
    {
      $unwind: "$driver_selection"
    },
    {
      $lookup: {
        "from": "drivers",
        "localField": "driver_selection",
        "foreignField": "id",
        "as": "result"
      }
    },
    {
      $unwind: "$result"
    },
    {
      $group: {
        "_id": "$id",
        "points": {
          $sum: "$result.driver_points"
        }
      }
    }
]);

这里是DEMO链接可以轻松测试它

希望它清晰且有帮助

© www.soinside.com 2019 - 2024. All rights reserved.