如何在MongoDB聚合中计算$ avg数组项?

时间:2019-12-12 04:48:17

标签: mongodb aggregation-framework 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]}
]

,我想在我的$avg查询中为此字段应用aggregation。我该怎么做才能使用mongodb获得整个数组的平均值?

我想要这样的结果

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

1 个答案:

答案 0 :(得分:0)

用$ 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"  
  }
}}]