Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在多个文档的嵌套数组中聚合MongoDB查询_Mongodb - Fatal编程技术网

在多个文档的嵌套数组中聚合MongoDB查询

在多个文档的嵌套数组中聚合MongoDB查询,mongodb,Mongodb,我正在做一个小的爱好项目为朋友的光盘高尔夫成绩 我对MongoDB还相当陌生,我一直坚持一个问题。我想做的是以[{player:“Name”,totalThrows:(Totalt字段之和),total+/-:(字段之和)}]的形式返回一个JSON对象 简言之:我想在我的数据库中的3个不同的文档中,汇总每个玩家的总投掷次数(总场数)和总+/- 最后一个JSON是这样的:[{player:“Tormod”,totalThrows:148,total+/-:24},{player:“Martin”,

我正在做一个小的爱好项目为朋友的光盘高尔夫成绩

我对MongoDB还相当陌生,我一直坚持一个问题。我想做的是以
[{player:“Name”,totalThrows:(Totalt字段之和),total+/-:(字段之和)}]
的形式返回一个JSON对象

简言之:我想在我的数据库中的3个不同的文档中,汇总每个玩家的总投掷次数(总场数)和总+/-

最后一个JSON是这样的:
[{player:“Tormod”,totalThrows:148,total+/-:24},{player:“Martin”,totalThrows:149,total+/-:25},{player:“Andreas”,totalThrows:158,total+/-:34}]

下图显示了我保存在MongoDB中的文档。结果数组由特定玩家的结果组成。在不同的文档中,结果数组中的第一个玩家也没有设置顺序。每个文档代表一个新的回合(考虑玩3天不同的游戏)

代码:


您应该将
\u id
字段(按表达式分组)传递给stage,并使用该字段对
Totalt
+/-
值求和。因为这些值是字符串,所以在求和之前应该使用将它们转换为整数。最后,可以基于所需的结构投影值

顺便说一句,看起来大多数数字字段都以字符串形式存储在文档中。我建议您更新文档,将它们全部转换为数字,并确保仅将数字添加到新文档中的数字字段中

db.collection.aggregate([
  {
    $unwind: "$results",
  },
  {
    $group: {
      _id: "$results.PlayerName",
      totalThrows: {
        $sum: {
          $toInt: "$results.Totalt",
        },
      },
      "total+/-": {
        $sum: {
          $toInt: "$results.+/-",
        },
      },
    },
  },
  {
    $project: {
      _id: 0,
      player: "$_id",
      totalThrows: "$totalThrows",
      "total+/-": "$total+/-",
    },
  },
])

你能分享一下你尝试过的吗?所以我尝试了很多不同的东西,最近我尝试过这样的东西:[{$unwind:$results”},{$group:{player:$results.PlayerName],抛出:“$results.Totalt”},{$group:{{u-id:$\u-id,totalThrows:{$sum:$results.Totalt“}}}}}})你能在问题中添加你的代码并与一些示例数据共享链接吗?完成@arunkumarmohanthegood!我想我已经接近了一半,非常感谢你Arun!@Kjott不客气。
db.collection.aggregate([
  {
    $unwind: "$results",
  },
  {
    $group: {
      _id: "$results.PlayerName",
      totalThrows: {
        $sum: {
          $toInt: "$results.Totalt",
        },
      },
      "total+/-": {
        $sum: {
          $toInt: "$results.+/-",
        },
      },
    },
  },
  {
    $project: {
      _id: 0,
      player: "$_id",
      totalThrows: "$totalThrows",
      "total+/-": "$total+/-",
    },
  },
])