简体   繁体   English

在聚合中使用计数 MongoDB

[英]Using count in aggregation MongoDB

Using the aggregation below I'm trying to find the number of conversations solved by a Chatbot or Agent in office and out of office hours.使用下面的聚合,我试图找到聊天机器人或代理在办公室和办公时间以外解决的对话数量。 With the aggregation below I'm getting a bunch of documents with the difference in solved and horario, which is 0 for out of office and 1 for in office conversations.通过下面的聚合,我得到了一堆文件,它们在已解决和 horario 方面存在差异,其中 0 代表不在办公室,1 代表办公室对话。 My current result is the following:我目前的结果如下:

结果对话

How can I get the following result, which adds up all the documents depending on the solved and the horario:我怎样才能得到以下结果,它根据已解决和 horario 将所有文档相加:

solved: Clipbot
horario: 0
count: 300

and

solved: Clipbot
horario: 1
count: 320

and

solved: Agent
horario: 0
count: 200

and

solved: Agent
horario: 1
count: 320

My current Aggregation:我目前的聚合:

[{$match: {
  start_date: {
    $gte: ISODate('2020-06-01 00:00:01'),
    $lte: ISODate('2020-06-30 23:59:59')
  }
}}, {$project: {
  solved: "$solved",
  hour: {
    $hour: {
      date: '$start_date',
      timezone: 'America/Mexico_City'
    }
  }
}}, {$project: {
  solved: "$solved",
  horario: {
    $cond: [
      {
        $and: [
        {
          $gt: [
            '$hour',
              7
          ]
          },
          {
            $lt: [
              '$hour',
                22
            ]
          },
        ]
      },
    1,
    0
    ]
  }
}}]

You can do with $group , i have not added other fields that you have added in your query,您可以使用$group ,我没有添加您在查询中添加的其他字段,

db.collection.aggregate([
  // you can add your $match conditions here
  {
    $group: {
      _id: {
        solved: "$solved",
        horario: "$horario"
      },
      count: { $sum: 1 },
      solved: { $first: "$solved" },
      horario: { $first: "$horario" }
    }
  },
  {
    $project: { _id: 0 }
  }
])

Working Playground: https://mongoplayground.net/p/gGWW7NXjaHy工作游乐场: https://mongoplayground.net/p/gGWW7NXjaHy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM