1.5 KiB
1.5 KiB
应用场景
9.3-9.30,开方时长0-30秒的医生名字及他们开的处方数(以此为例)
说明
后期可自行修改下面代码中查询条件($match)来实现需求
方案 mongosh
代码
01. 切换到目标数据库
use Internet-hospital;
02. 执行聚合查询
db["hlw-doctor-times"].aggregate([
// 1. 过滤条件:筛选指定时间范围和 符合rxDuration 的文档
{
$match: {
createTime: {
// 转换为毫秒时间戳(UTC 时间 2025-09-03 00:00:00)
$gte: new Date("2025-09-03").getTime(),
// 转换为毫秒时间戳(UTC 时间 2025-10-01 00:00:00,覆盖到 9-30 最后一刻)
$lt: new Date("2025-10-01").getTime()
},
rxDuration: { $lte: 30000 } // rxDuration 小于等于 30000
}
},
// 2. 分组统计:按 doctorCode 分组,计算每个医生的符合条件文档数
{
$group: {
_id: "$doctorCode", // 分组键:doctorCode
doctorName: { $first: "$doctorName" }, // 取同组第一个医生姓名(确保唯一)
count: { $sum: 1 } // 统计每组文档数
}
},
// 3. 格式化输出:调整字段结构,符合需求格式 { doctorCode, doctorName, count }
{
$project: {
_id: 0, // 隐藏默认的 _id 字段
doctorCode: "$_id", // 将分组键 _id 转为 doctorCode
doctorName: 1, // 保留医生姓名
count: 1 // 保留统计数量
}
}
]).toArray();