// 获取昨天的日期
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
const startOfYesterday = new Date(yesterday.getFullYear(), yesterday.getMonth(), yesterday.getDate());
const endOfYesterday = new Date(yesterday.getFullYear(), yesterday.getMonth(), yesterday.getDate() + 1);
db.logs.aggregate([
{
$match: {
timestamp: {
$gte: startOfYesterday,
$lt: endOfYesterday
}
}
},
{
$group: {
_id: {
service: "$service",
operation: "$operation"
},
totalDuration: { $sum: "$duration" },
count: { $sum: 1 }
}
},
{
$addFields: {
averageDuration: { $divide: ["$totalDuration", "$count"] }
}
},
{
$sort: {
"_id.service": 1,
averageDuration: -1
}
},
{
$group: {
_id: "$_id.service",
topOperations: {
$push: {
operation: "$_id.operation",
averageDuration: "$averageDuration"
}
}
}
},
{
$addFields: {
topOperations: {
$slice: ["$topOperations", 5]
}
}
}
]);