优化 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 批量返回各亚模块最近一次内容审核通过时间。
|
// 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) {
|
func LatestReviewAtByModules(moduleIDs []string) (map[string]time.Time, error) {
|
||||||
result := make(map[string]time.Time, len(moduleIDs))
|
result := make(map[string]time.Time, len(moduleIDs))
|
||||||
if len(moduleIDs) == 0 {
|
if len(moduleIDs) == 0 {
|
||||||
@@ -39,15 +42,20 @@ func LatestReviewAtByModules(moduleIDs []string) (map[string]time.Time, error) {
|
|||||||
{"$match": bson.M{
|
{"$match": bson.M{
|
||||||
"status": CheckPass,
|
"status": CheckPass,
|
||||||
"mId": bson.M{"$in": moduleIDs},
|
"mId": bson.M{"$in": moduleIDs},
|
||||||
"reviewAt": bson.M{"$gt": time.Time{}},
|
|
||||||
}},
|
}},
|
||||||
|
{"$sort": bson.D{{Key: "mId", Value: 1}, {Key: "reviewAt", Value: -1}}},
|
||||||
{"$group": bson.M{
|
{"$group": bson.M{
|
||||||
"_id": "$mId",
|
"_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
|
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
|
return nil, err
|
||||||
}
|
}
|
||||||
for _, row := range rows {
|
for _, row := range rows {
|
||||||
|
|||||||
Reference in New Issue
Block a user