计算对象数组字段的总和

时间:2020-05-07 21:09:58

标签: node.js mongodb express

使用Express作为Web框架,使用Mongo作为后端的Node App。目前,我有一个Mongoose数据架构,其中包含播放器和相关的统计信息。这是该结构的匿名示例:

  name: 'Player Name',
  image: 'image-location',
  position: 'Guard',
  description: 'Player Detail',
  __v: 6,
  weight: 200,
  dob: 1993-08-03T05:00:00.000Z,
  hometown: 'town-name',
  country: 'country-name',
  height_feet: 6,
  height_inches: 4,
  season: [
    {
      year: '2012-2013',
      grade: 'Freshman',
      gp: 18,
      gs: 0,
      mpg: 6.9,
      fg: 0.348,
      tp: 0.278,
      ft: 1,
      rpg: 0.8,
      apg: 1,
      spg: 0.3,
      bpg: 0,
      ppg: 1.4
    },
    {
      year: '2013-2014',
      grade: 'Sophomore',
      gp: 36,
      gs: 7,
      mpg: 20.3,
      fg: 0.432,
      tp: 0.4,
      ft: 0.643,
      rpg: 1.6,
      apg: 1.1,
      spg: 0.2,
      bpg: 0.1,
      ppg: 7.1
    },
    {
      year: '2014-2015',
      grade: 'Junior',
      gp: 34,
      gs: 33,
      mpg: 27.5,
      fg: 0.449,
      tp: 0.391,
      ft: 0.755,
      rpg: 2.9,
      apg: 2,
      spg: 0.8,
      bpg: 0.1,
      ppg: 10.1
    },
    {
      year: '2015-2016',
      grade: 'R. Senior',
      gp: 8,
      gs: 8,
      mpg: 31.6,
      fg: 0.425,
      tp: 0.291,
      ft: 0.6,
      rpg: 2.9,
      apg: 1.9,
      spg: 0.6,
      bpg: 0.3,
      ppg: 12
    },
    {
      year: '2016-2017',
      grade: 'Senior',
      gp: 35,
      gs: 35,
      mpg: 33.3,
      fg: 0.473,
      tp: 0.384,
      ft: 0.795,
      rpg: 4.6,
      apg: 2.7,
      spg: 1.2,
      bpg: 0,
      ppg: 15.1
    }
  ]

}

作为一个整体,我对Mongo和Node还是很陌生,所以请忽略基本问题。如何计算特定统计数据在总赛季数中的平均值(例如,每场比赛的4年平均值)?

此处的目标是计算值并使它可用,并在播放器页面的GET路由上传递该值。这是我进入播放器页面的路线:

router.get("/:id", function(req, res){
    Player.findById(req.params.id).populate("comments").exec(function(err, foundPlayer){
        if(err){
            console.log(err);
        } else {
            console.log(foundPlayer)
            res.render("players/show", {player: foundPlayer});
        }
    });
});

该如何计算该值并使它可在播放器页面上使用?

1 个答案:

答案 0 :(得分:1)

我们可以使用聚合管道直接在查询中计算平均值

db.collection.aggregate([
  {
    $match: {
      _id: "playerId1" // this needs to be of type ObjectId, it should be something like mongoose.Types.ObjectId(req.params.id) in your case
    }
  },
  {
    $unwind: "$season" // unwind the season array to get a stream of documents, and to be able to calculate the average of ppg
  },
  {
    $group: { // then group them again
      _id: "$_id",
      averagePointsPerGame: {
        $avg: "$season.ppg"
      },
      season: {
        $push: "$season"
      }
    }
  }
])

您可以在Mongo Playground

进行测试

希望有帮助