仅查询嵌套数组中的数字

时间:2018-10-01 05:34:33

标签: arrays mongodb aggregation-framework average

我正在尝试获取文档内部嵌套数组中键的平均数量,但不确定如何实现。

这是我的文档的样子:

{
  "_id": {
    "$oid": "XXXXXXXXXXXXXXXXX"
  },
  "data": {
    "type": "PlayerRoundData",
    "playerId": "XXXXXXXXXXXXX",
    "groupId": "XXXXXXXXXXXXXX",
    "holeScores": [
      {
        "type": "RoundHoleData",
        "points": 2
      },
      {
        "type": "RoundHoleData",
        "points": 13
      },
      {
        "type": "RoundHoleData",
        "points": 3
      },
      {
        "type": "RoundHoleData",
        "points": 1
      },
      {
        "type": "RoundHoleData",
        "points": 21
      }
    ]
  }
}

现在,棘手的部分是,我只想要具有该playerid和该groupid的所有文档的HoleScores [0]的平均点数。

实际上,最好的解决方案是收集具有playerid和groupid的所有文档,并创建一个平均数组HoleScores [0],holeScores [1],holeScores [2]的新数组。但是如果我只能得到一个数组键,那对:-)

这是我的想法,但不确定要如何将其组合在一起:

var allScores = dbCollection('scores').aggregate(
    {$match: {"data.groupId": groupId, "playerId": playerId}},
    {$group: {
        _id: playerId, 
        rounds: { $sum: 1 }
        result: { $sum: "$data.scoreTotals.points" }
    }}
);

真的希望在此问题上寻求帮助,并在此先感谢:-)

2 个答案:

答案 0 :(得分:1)

您可以尝试以下汇总

db.collection.aggregate(
  { "$match": { "data.groupId": groupId, "data.playerId": playerId }},
  { "$group": {
    "_id": null,
    "result": {
      "$sum": {
        "$arrayElemAt": [
          "$data.holeScores.points",
          0
        ]
      }
    }
  }}
)

答案 1 :(得分:1)

您可以将$unwindincludeArrayIndex一起使用来获取索引,然后使用$group对该索引进行分组

dbCollection('scores').aggregate(
    {
        $match: { "data.playerId": "XXXXXXXXXXXXX", "data.groupId": "XXXXXXXXXXXXXX" }
    },
    {
        $unwind: {
            path: "$data.holeScores",
            includeArrayIndex: "index"
        }
    },
    {
        $group: {
            _id: "$index",
            playerId: { $first: "data.playerId" }, 
            avg: { $avg: "$data.holeScores.points" }
        }
    }
)