MongoDB在汇总组中真实计数

时间:2019-03-11 07:44:16

标签: mongodb grouping aggregate conditional-statements

我正在尝试以一种简单的方式对一些统计数据进行平均和求和,但是遇到了麻烦!

我收集了一些具有如下统计数据的文档:

{
  "playerId": "5c6024b5031f5bc44d790e01",
  "courseId": "5b2a0ab1c6dc0f04e9a1e769",
  "gir": true,
  "data": {
    "roundHoles": [
      {
        "type": "HoleData",
        "holeNo": 1,
        "par": 3,
        "hcp": 18
      },
      {
        "type": "HoleData",
        "holeNo": 2,
        "par": 4,
        "hcp": 4
      },
      {
        "type": "HoleData",
        "holeNo": 3,
        "par": 4,
        "hcp": 8
      }
    ],
    "holeScores": [
      {
        "type": "RoundHoleData",
        "strokes": 3,
        "points": 2,
        "puts": 1,
        "gir": true,
        "scrambled": false
      },
      {
        "type": "RoundHoleData",
        "strokes": 5,
        "points": 1,
        "puts": 2,
        "gir": false,
        "scrambled": false
      },
      {
        "type": "RoundHoleData",
        "strokes": 4,
        "points": 2,
        "puts": 1,
        "gir": false,
        "scrambled": true
      }
    }
  }
}

我想做的是获得真实的平均笔画,得分和看跌以及加扰和吉尔的总和,只有当主“吉尔”设置为“真”时才bur。

这是我到目前为止提出的:

var allScores = runtimeCollection('roundScores').aggregate(
  {
      $match: { "playerId": playerId, "courseId": "5b2a0ab1c6dc0f04e9a1e769" }
  },
  {
      $unwind: {
          path: "$data.holeScores",
          includeArrayIndex: "index"
      }
  },
  {
      $group: {
          _id: "$index",
          rounds: { $sum: 1 },
          avgStrokes: { $avg: "$data.holeScores.strokes" },
          avgPoints: { $avg: "$data.holeScores.points" },
          avgPuts: { $avg: "$data.holeScores.puts" },
          sumScrambles: { $sum: "$data.holeScores.scrambled" }
      }
  }
);

这就是我从中得到的:

{
  "_id": 17,
  "rounds": 18,
  "avgStrokes": 3.4444444444444446,
  "avgPoints": 1.2777777777777777,
  "avgPuts": 1.6111111111111112,
  "sumScrambles": 0
},
{
  "_id": 14,
  "rounds": 18,
  "avgStrokes": 5.388888888888889,
  "avgPoints": 2.1666666666666665,
  "avgPuts": 1.5,
  "sumScrambles": 0
},
{
  "_id": 12,
  "rounds": 18,
  "avgStrokes": 5,
  "avgPoints": 1.6111111111111112,
  "avgPuts": 1.8333333333333333,
  "sumScrambles": 0
}

看起来我得到的平均零件很好,但是总和不起作用。我想我必须在sumScrambles中添加一个条件,但不确定如何?

真的希望有人可以帮助我,在此先感谢:-)

1 个答案:

答案 0 :(得分:1)

好吧,首先,您无法获取布尔值的总和,只能获取数字的总和。因此,我假设您希望在加扰的值为true时加1,在这种情况下,您可以使用'$cond',从而允许您编写条件。

您可以尝试这样的事情,

eslint