如何计算 MongoDB 聚合中数组项的 $average?

How to calculate $avg of array items in MongoDB aggregation?

我正在构建一个 mongodb aggregation 查询,其中我有一个数值的计算字段(数组)。而且我必须找到整个数组字段的平均值。我的mongodb聚合查询是这样的

[{$match: {
  nsp: '/globalintltd.com',
  agentEmail: 'ahmed1549@globalintltd.com'
}}, {$lookup: {
  from: 'messages',
  let : {cid : '$_id'},
  pipeline:[
    {
      $match : {
        $expr:{
          $eq: ['$cid', '$$cid'],
        },
        type: 'Agents'
      }
    },
    {$limit : 1}
  ],
  as: 'messages'
}}, {$project: {
  agentEmail: 1,
  convDate: {
    $dateFromString:{
      dateString: '$createdOn'
    }
  },
  firstReplyDate:{
    $dateFromString:{
      dateString:{
        $arrayElemAt:['$messages.date', 0]
      }
    }
  }
}}, {$addFields: {
  difference: {
    $divide:[
      {
         $subtract:[
    '$firstReplyDate',
    '$convDate'
    ] 
      },
      60000
    ]
  }
}}, {$group: {
  _id: {
    "agentEmail" : "$agentEmail"
  },
  AgentFirstResponses : {
    $push : "$difference"  
  }
}}]

从上面的查询我得到这样的结果

[
  {agentEmail : "ahmed1549@globalintltd.com", convId : 3434345111, AgentFirstResponses : [33.54,65.65,9.087,5.43]},
  {agentEmail : "ahmed1549@globalintltd.com", convId : 3434345112, AgentFirstResponses : [3.54,65.165,19.087,1.43]},
  {agentEmail : "ahmed1549@globalintltd.com", convId : 3434345113, AgentFirstResponses : [63.54,654.65,19.087,5.43]},
  {agentEmail : "ahmed1549@globalintltd.com", convId : 3434345114, AgentFirstResponses : [33.54,65.65,9.087,5.43]}
]

我想在我的 aggregation 查询中为该字段应用 $avg。我怎样才能使用 mongodb?

获得整个数组的平均值

我想要这样的结果

{
  "agentEmail" : "ahmed1549@globalintltd.com",
  "AvgFirstResponse" : 23.665(what ever average will of the whole array)
}

像这样用 $avg 替换 $push:

[{$match: {
  nsp: '/globalintltd.com',
  agentEmail: 'ahmed1549@globalintltd.com'
}}, {$lookup: {
  from: 'messages',
  let : {cid : '$_id'},
  pipeline:[
    {
      $match : {
        $expr:{
          $eq: ['$cid', '$$cid'],
        },
        type: 'Agents'
      }
    },
    {$limit : 1}
  ],
  as: 'messages'
}}, {$project: {
  agentEmail: 1,
  convDate: {
    $dateFromString:{
      dateString: '$createdOn'
    }
  },
  firstReplyDate:{
    $dateFromString:{
      dateString:{
        $arrayElemAt:['$messages.date', 0]
      }
    }
  }
}}, {$addFields: {
  difference: {
    $divide:[
      {
         $subtract:[
    '$firstReplyDate',
    '$convDate'
    ] 
      },
      60000
    ]
  }
}}, {$group: {
  _id: {
    "agentEmail" : "$agentEmail"
  },
  AgentFirstResponses : {
    $avg : "$difference"  
  }
}}]