---
title: MongoDB 聚合管道与索引优化实战
keywords:
- MongoDB
- 聚合
- 复合索引
- explain
- hint
description: 结合复合索引与聚合管道提升查询与统计性能,提供可执行的索引与管道示例。
tags:
- MongoDB
- explain
- hint
- 复合索引
- 性能优化
- 数据库
- 聚合
categories:
- 文章资讯
- 技术教程
---
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 验证计划与命中,可获得稳定的性能收益。

发表评论 取消回复