如何在MongoDB和Java中计算文档数组外的字段与文档数组内的字段之间的平均值?

问题描述

我的数据库中有此文档:

[
  {
    "_id": {
      "$oid": "5f5f280ffa2236115655cb6a"
    },"Name": "Rovilio Chipman","Last_season": {
      "year": "2010-2011","goals": 10,"assists": 1
    },"Last_season_2": {
      "year": "2011-2012","goals": 1,"assists": 12
    },"Seasons": [
      {
        "year": "2012-2013","goals": 11,"assists": 4
      },{
        "year": "2013-2014","goals": 6,"assists": 2
      },{
        "year": "2014-2015","goals": 5,"assists": 5
      }
    ]
  }
]

我想获得所有目标的平均值,即“过去的季节”,“过去的季节_2”和“季节”中包含的目标的平均值。结果应为33/5 = 6.6。

注意:要求平均值的文档大小不同,即“季节”数组可以包含不同数量的文档,并且不是固定的。

在这种情况下,如何计算该平均值?如何使用Java驱动程序进行编码?

解决方法

首先,您需要将所有值放在一个数组中,然后可以计算平均值。这可能是一种解决方案:

db.collection.aggregate([
  {
    $set: {
      AllSeasons: {
        $concatArrays: [
          "$Seasons",[ "$Last_season" ],[ "$Last_season_2" ]
        ]
      }
    }
  },{ $set: { average: { $avg: [ "$AllSeasons.goals" ] } } },{ $unset: "AllSeasons" }
])

Mongo Playground

,

您可以使用mongo聚合来实现。

Encoding

try it


这是有关MongoDB aggregation with Java driver

的帖子 ,

请检查是否适合您

goto

Mongo Playground