MongoDB 聚合管道与索引优化实战索引db.users.createIndex({ status: 1, createdAt: -1 }); db.orders.createIndex({ userId: 1, createdAt: -1 }); 聚合管道db.orders.aggregate([ { $match: { status: 'paid', createdAt: { $gte: ISODate('2025-11-01T00:00:00Z') } } }, { $group: { _id: '$userId', total: { $sum: '$amount' } } }, { $sort: { total: -1 } }, { $limit: 10 } ]); 解释与优化db.orders.find({ userId: 123 }).hint({ userId: 1 }).explain('executionStats'); 总结针对查询与统计路径设置匹配的复合索引,并用 explain 验证计划与命中,可获得稳定的性能收益。

发表评论 取消回复