Spring Boot操作MongoDB的完整示例大全

以下是基于Spring Boot操作MongoDB的完整示例大全,涵盖增删改查、聚合查询、索引、事务等核心功能:


一、基础CRUD操作

1. 环境配置

依赖配置(pom.xml)

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

核心配置(application.yml)

yaml 复制代码
spring:
  data:
    mongodb:
      uri: mongodb://root:123456@192.168.3.11:27017/mydb?authSource=admin
      # 或分开配置
      host: 192.168.3.11
      port: 27017
      username: root
      password: 123456
      authentication-database: admin

2. 实体类定义

java 复制代码
@Data
@Document(collection = "users") // 指定集合名
public class User {
    @Id
    private String id;
    
    @Indexed(direction = IndexDirection.ASCENDING) // 单字段索引
    private String name;
    
    @TextIndexed // 全文索引
    private String email;
    
    private Integer age;
    private Date createDate;
}

3. Repository接口

java 复制代码
public interface UserRepository extends MongoRepository<User, String> {
    // 方法名推导查询
    List<User> findByName(String name);
    
    // 自定义JSON查询
    @Query("{ 'age' : { $gt: ?0 } }")
    List<User> findByAgeGreaterThan(int age);
}

4. MongoTemplate操作

java 复制代码
@Autowired
private MongoTemplate mongoTemplate;

// 插入文档
User user = new User();
user.setId(UUID.randomUUID().toString());
user.setName("Alice");
mongoTemplate.insert(user); // 插入单个文档

// 查询所有
List<User> users = mongoTemplate.findAll(User.class);

// 根据ID查询
User user = mongoTemplate.findById("1001", User.class);

// 条件查询
Query query = new Query();
query.eq("name", "Alice").gt("age", 20);
List<User> result = mongoTemplate.find(query, User.class);

// 更新文档
Update update = new Update();
update.set("name", "NewName").inc("age", 1);
mongoTemplate.updateFirst(Query.query(Criteria.where("id").is("1001")), update, User.class);

// 删除文档
mongoTemplate.remove(Query.query(Criteria.where("id").is("1001")), User.class);

二、聚合查询操作

1. 使用Aggregation API

java 复制代码
// 聚合管道:匹配+分组统计
Aggregation aggregation = Aggregation.newAggregation(
    Aggregation.match(Criteria.where("age").gt(18)), // 过滤年龄>18
    Aggregation.group("department") // 按部门分组
        .count().as("total") // 统计人数
        .avg("salary").as("avgSalary"), // 计算平均工资
    Aggregation.sort(Sort.Direction.DESC, "total") // 按总人数降序排序
);

// 执行聚合
AggregationResults<Document> results = mongoTemplate.aggregate(aggregation, "users", Document.class);

2. 原生JSON聚合

java 复制代码
// 直接使用JSON格式定义聚合管道
String pipeline = "[{ $match: { age: { $gt: 18 } } }, " +
                 "{ $group: { _id: '$department', total: { $sum: 1 }, avgSalary: { $avg: '$salary' } } }, " +
                 "{ $sort: { total: -1 } }]";

AggregationResults<Document> results = mongoTemplate.aggregate(
    new BasicQuery(pipeline), "users", Document.class);

三、高级功能实现

1. 全文搜索

java 复制代码
// 1. 创建文本索引
@TextIndexed
private String title;

// 2. 使用TextCriteria查询
public List<Note> searchNotes(String keyword) {
    TextCriteria criteria = TextCriteria.forDefaultLanguage().matching(keyword);
    Query query = new Query(criteria);
    return mongoTemplate.find(query, Note.class);
}

2. 事务管理

java 复制代码
@Configuration
@EnableTransactionManagement
public class MongoConfig {
    @Bean
    public MongoTransactionManager transactionManager(MongoDatabaseFactory factory) {
        return new MongoTransactionManager(factory);
    }
}

// 服务层使用@Transactional
@Service
public class TransferService {
    @Transactional
    public void transferMoney(String fromId, String toId, double amount) {
        // 扣减转出账户
        mongoTemplate.updateFirst(Query.query(Criteria.where("id").is(fromId)), 
            new Update().inc("balance", -amount), Account.class);
        
        // 增加转入账户
        mongoTemplate.updateFirst(Query.query(Criteria.where("id").is(toId)), 
            new Update().inc("balance", amount), Account.class);
    }
}

3. 连接池调优

yaml 复制代码
spring:
  data:
    mongodb:
      uri: mongodb://user:pass@host:27017/db?
          maxIdleTimeMS=300000&
          maxPoolSize=100&
          minPoolSize=10&
          maxWaitTimeMS=1000

四、性能优化技巧

1. 分页查询

java 复制代码
// 使用Pageable实现分页
Pageable pageable = PageRequest.of(0, 10, Sort.by("age").descending());
Query query = new Query().with(pageable);
List<User> users = mongoTemplate.find(query, User.class);

2. 复合索引

java 复制代码
@CompoundIndexes({
    @CompoundIndex(name = "name_age_index", def = "{'name': 1, 'age': -1}")
})
public class User {}

3. 地理位置查询

java 复制代码
// 创建2D索引
@Field(store = true, indexDirection = Direction.GEO2D)
private Point location;

// 查询附近5公里内的用户
Query query = new Query();
query.near("location", new GeoJsonPoint(116.4, 39.9)).maxDistance(5000);
List<User> nearbyUsers = mongoTemplate.find(query, User.class);

五、常见异常处理

  1. 连接超时 :检查URI配置和网络连通性,适当增加connectTimeoutMS
  2. 查询无结果 :确认数据存在且索引生效,可使用hint()强制指定索引
  3. 事务冲突:确保操作集合已存在并启用副本集
  4. 内存溢出 :聚合查询时添加allowDiskUse(true)

完整代码示例可参考CSDN专题教程,生产环境建议结合分库分表、读写分离等高级架构设计。

相关推荐
程序员岳焱6 小时前
Java 与 MySQL 性能优化:Java 实现百万数据分批次插入的最佳实践
后端·mysql·性能优化
麦兜*6 小时前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
KK溜了溜了7 小时前
JAVA-springboot 整合Redis
java·spring boot·redis
大只鹅7 小时前
解决 Spring Boot 对 Elasticsearch 字段没有小驼峰映射的问题
spring boot·后端·elasticsearch
ai小鬼头7 小时前
AIStarter如何快速部署Stable Diffusion?**新手也能轻松上手的AI绘图
前端·后端·github
天河归来7 小时前
使用idea创建springboot单体项目
java·spring boot·intellij-idea
IT_10247 小时前
Spring Boot项目开发实战销售管理系统——数据库设计!
java·开发语言·数据库·spring boot·后端·oracle
bobz9658 小时前
动态规划
后端
stark张宇8 小时前
VMware 虚拟机装 Linux Centos 7.9 保姆级教程(附资源包)
linux·后端
武昌库里写JAVA8 小时前
Oracle如何使用序列 Oracle序列使用教程
java·开发语言·spring boot·学习·课程设计