From 1d1101fc3bb5fc8876ec4db8e32dba2240c32b8e Mon Sep 17 00:00:00 2001 From: root Date: Thu, 5 Nov 2026 11:09:07 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=20LatestReviewAtByModules=20?= =?UTF-8?q?=E8=81=9A=E5=90=88=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用 $sort + $group($first) + hint 替代 $max,配合复合索引 {mId:1,status:1,reviewAt:-1} 减少 key examined。 Co-Authored-By: Claude Opus 4.7 --- models/v/vidmod/update_marker.go | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/models/v/vidmod/update_marker.go b/models/v/vidmod/update_marker.go index 123225a..6687efb 100644 --- a/models/v/vidmod/update_marker.go +++ b/models/v/vidmod/update_marker.go @@ -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 {