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

我是新来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"
        }
      }
    }
  ])

推荐答案

一种 Select 是使用$lookup$sum:

db.players.aggregate([
  {$lookup: {
      from: "drivers",
      localField: "driver_selection",
      foreignField: "id",
      as: "total_points",
      pipeline: [{$project: {driver_points: 1, _id: 0}}]
  }},
  {$set: {total_points: {$sum: "$total_points.driver_points"}}},
  {$merge: {into: "players"}}
])

看看它在playground example号公路上是如何工作的

$unwind被认为是一个昂贵的操作,没有必要在这里使用它.$lookup可以在数组上工作,$sum更容易.

管道只允许您从另一个集合中获取所需的数据.

一百:

添加了更新集合的最后$merge步.

Mongodb相关问答推荐

MongoDB - 将属性添加到数组中的对象(如果不存在)

在不知道字段名称的情况下如何引用 MongoDB 中的字段?

pymongo - ifnull 重新调整整个对象而不是特定字段

Golang:如何判断 collection.Find 是否没有找到任何文件?

分页时根据唯一字段mongodb获取数据

根据聚合管道MongoDB Atlas触发器中的条件更新多个字段

使用 EventSourcing(NodeJS、MongoDB、JSON)跨多个偶尔连接的客户端同步数据

MongoDB .NET 未在 upsert 上生成 _id

MongoDB获取聚合查询的executionStats

加载时将 mongo 存储的日期转换回自 Unix 纪元以来的毫秒数?

Node.js 和 Passport 对象没有方法 validPassword

Springboot 使用 find*() 查询时出现 Mongodb 错误

是否有适用于 Linux 的 MongoDB GUI 桌面应用程序?

将 mongodb 聚合框架结果导出到新集合

如何根据其他字段添加条件模式?

在 MongoDB 中合并两个集合

判断 mongoDB 是否连接

了解 Mongoose 中的关系和外键

MongoDB Compass timeouts超时

在 mongodb 集合中查找最旧/最新的帖子