优化 LatestReviewAtByModules 聚合查询
用 $sort + $group($first) + hint 替代 $max,配合复合索引
{mId:1,status:1,reviewAt:-1} 减少 key examined。
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -30,6 +30,9 @@ func LatestReviewAt(filter bson.M) (*time.Time, error) {
|
||||
}
|
||||
|
||||
// LatestReviewAtByModules 批量返回各亚模块最近一次内容审核通过时间。
|
||||
// 用 $sort + $group($first) + hint 替代 $max:
|
||||
// 配合 {mId:1,status:1,reviewAt:-1} 索引后,MongoDB 对每个 mId 只扫到首个 key 即可返回,
|
||||
// 相较 $max 需要全量扫描所有匹配 key,key examined 可从数万级降到约 len(moduleIDs)。
|
||||
func LatestReviewAtByModules(moduleIDs []string) (map[string]time.Time, error) {
|
||||
result := make(map[string]time.Time, len(moduleIDs))
|
||||
if len(moduleIDs) == 0 {
|
||||
@@ -37,17 +40,22 @@ func LatestReviewAtByModules(moduleIDs []string) (map[string]time.Time, error) {
|
||||
}
|
||||
pipeline := []bson.M{
|
||||
{"$match": bson.M{
|
||||
"status": CheckPass,
|
||||
"mId": bson.M{"$in": moduleIDs},
|
||||
"reviewAt": bson.M{"$gt": time.Time{}},
|
||||
"status": CheckPass,
|
||||
"mId": bson.M{"$in": moduleIDs},
|
||||
}},
|
||||
{"$sort": bson.D{{Key: "mId", Value: 1}, {Key: "reviewAt", Value: -1}}},
|
||||
{"$group": bson.M{
|
||||
"_id": "$mId",
|
||||
"latestAt": bson.M{"$max": "$reviewAt"},
|
||||
"latestAt": bson.M{"$first": "$reviewAt"},
|
||||
}},
|
||||
}
|
||||
opts := options.Aggregate().SetHint(bson.D{
|
||||
{Key: "mId", Value: 1},
|
||||
{Key: "status", Value: 1},
|
||||
{Key: "reviewAt", Value: -1},
|
||||
})
|
||||
var rows []ModuleLatestAt
|
||||
if err := coll(nil).Aggregate(&rows, pipeline); err != nil {
|
||||
if err := coll(nil).Aggregate(&rows, pipeline, opts); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
|
||||
Reference in New Issue
Block a user