MongoTemplate 性能优化指南
1. 查询优化
1.1 合理使用索引
- 为经常查询的字段创建索引
- 使用复合索引优化多字段查询
- 避免使用无索引的排序操作
// 创建索引示例
mongoTemplate.indexOps(Collection.class).ensureIndex(
new Index().on("field1", Sort.Direction.ASC)
.on("field2", Sort.Direction.DESC)
);
1.2 投影查询
- 只查询需要的字段,减少数据传输量
Query query = new Query();
query.fields().include("name").include("age").exclude("id");
List<User> users = mongoTemplate.find(query, User