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 Mongo查询分组并使用分组依据计算平均值_Mongodb_Average - Fatal编程技术网

Mongodb Mongo查询分组并使用分组依据计算平均值

Mongodb Mongo查询分组并使用分组依据计算平均值,mongodb,average,Mongodb,Average,我有一个具有以下结构的mongo集合mytopic: id : ObjectId host: String analytics: Object topic_count : Array name: String mentions: Int duration: Float percentage: Float 我想按analytics.topic_count.name分组,并返回每个用户的平均持续时间。 我的预期产出是:

我有一个具有以下结构的mongo集合mytopic:

id : ObjectId
host: String
analytics: Object
    topic_count : Array
         name: String
         mentions: Int
         duration: Float
         percentage: Float
我想按analytics.topic_count.name分组,并返回每个用户的平均持续时间。 我的预期产出是:

Topic1:      User1: <Average of duration for Topic1>
             User2: <float>
             User3: <float>
             User4: <float>
             User5: <float>

Topic2       User1: <float>
             User2: <float>
             User3: <float>
             User4: <float>
             User5: <float>

你在找这样的东西吗

db.collection.aggregate([
  {
    "$unwind": "$analytics.topic_count"
  },
  {
    "$group": {
      "_id": {
        topic: "$analytics.topic_count.name",
        host: "$host"
      },
      "duration": {
        "$avg": "$analytics.topic_count.duration"
      }
    }
  },
  {
    "$group": {
      "_id": "$_id.topic",
      "durations": {
        "$addToSet": {
          "$mergeObjects": [
            {
              "host": "$_id.host"
            },
            {
              "duration": "$duration"
            }
          ]
        }
      }
    }
  }
])

这里正在工作

工作得很好。非常感谢。
db.collection.aggregate([
  {
    "$unwind": "$analytics.topic_count"
  },
  {
    "$group": {
      "_id": {
        topic: "$analytics.topic_count.name",
        host: "$host"
      },
      "duration": {
        "$avg": "$analytics.topic_count.duration"
      }
    }
  },
  {
    "$group": {
      "_id": "$_id.topic",
      "durations": {
        "$addToSet": {
          "$mergeObjects": [
            {
              "host": "$_id.host"
            },
            {
              "duration": "$duration"
            }
          ]
        }
      }
    }
  }
])