一、maven中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
二、配置文件中添加连接
spring:
mongodb:
host: 192.168.56.10
port: 27017
database: share #指定操作的数据库
三、创建mongodb文档对应的实体类
@Data
@Schema(description = "站点位置")
public class StationLocation
{
@Schema(description = "id")
@Id
private String id;
@Schema(description = "站点id")
private Long stationId;
@Schema(description = "经纬度")
private GeoJsonPoint location;
@Schema(description = "创建时间")
private Date createTime;
}
四、操作MongoDB数据库
Springboot提供了5种操作MongoDB的方式,下面简单介绍下它们的使用方法:
4.1 MongoTemplate
特点:
是 Spring Data MongoDB 提供的核心模板类
提供丰富的 CRUD 操作方法
支持复杂的查询和聚合操作
需要手动编写查询逻辑
示例代码:
查询:
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
// 注入
@Autowired
private MongoTemplate mongoTemplate;
// 调用mongoTemplate,查询周边数据
// 查询指定经纬度附近的站点
public List<StationLocation> nearbyStation(String latitude, String longitude) {
//确定中心点,根据经纬度获取站点信息
GeoJsonPoint point = new GeoJsonPoint(Double.parseDouble(longitude), Double.parseDouble(latitude));
//设置查询半径,查询站点周边50公里范围的信息
Distance distance = new Distance(50, Metrics.KILOMETERS);
//画圆 确定查询范围
Circle circle = new Circle(point, distance);
//查询MongoDB数据库中站点信息
Query query = new Query(Criteria.where("location").withinSphere(circle));
List<StationLocation> stations = mongoTemplate.find(query, StationLocation.class);
}
4.2 MongoRepository
特点:
基于 JPA 风格的 Repository 接口
支持方法名自动生成查询
提供基本的 CRUD 操作
可通过注解扩展自定义查询
适合简单的 CRUD 操作
示例代码:
创建Repository的接口
//StationLocation为要查询的文档对应的实体类,String为实体类StationLocation主键的类型
public interface StationLocationRepository extends MongoRepository<StationLocation, String> {
//方法要规范命名,mongodb才能按图索骥找到对应的数据
StationLocation getByStationId(Long id);
}
调用上面定义的Repository新增插入数据:
@Autowired
private StationLocationRepository stationLocationRepository;
public int saveStation(Station station) {
String provinceName = regionService.getNameByCode(station.getProvinceCode());
String cityName = regionService.getNameByCode(station.getCityCode());
String districtName = regionService.getNameByCode(station.getDistrictCode());
station.setFullAddress(provinceName + cityName + districtName + station.getAddress());
int rows = stationMapper.insert(station);
StationLocation stationLocation = new StationLocation();
stationLocation.setId(ObjectId.get().toString());
stationLocation.setStationId(station.getId());
stationLocation.setLocation(new GeoJsonPoint(station.getLongitude().doubleValue(), station.getLatitude().doubleValue()));
stationLocation.setCreateTime(new Date());
stationLocationRepository.save(stationLocation);
return rows;
}
修改数据
@Autowired
private StationLocationRepository stationLocationRepository;
public int updateStation(Station station) {
StationLocation stationLocation = stationLocationRepository.getByStationId(station.getId());
stationLocation.setLocation(new GeoJsonPoint(station.getLongitude().doubleValue(), station.getLatitude().doubleValue()));
stationLocationRepository.save(stationLocation);
return rows;
}
4.3 ReactiveMongoTemplate
特点:
响应式编程模型的 MongoTemplate
返回 Mono 或 Flux 类型
适合非阻塞、异步应用
需要 Spring WebFlux 环境
示例代码:
@Autowired
private ReactiveMongoTemplate reactiveMongoTemplate;
public Mono<User> findUserById(String id) {
return reactiveMongoTemplate.findById(id, User.class);
}
4.4 ReactiveMongoRepository
特点:
响应式版本的 MongoRepository
返回 Publisher 类型 (Mono/Flux)
支持响应式流处理
适合全栈响应式应用
示例代码:
// 创建ReactiveRepository
public interface UserReactiveRepository extends ReactiveMongoRepository<User, String> {
Flux<User> findByName(String name);
}
// 使用
@Autowired
private UserReactiveRepository userReactiveRepository;
4.5 原生 MongoDB Java 驱动
特点:
直接使用 MongoDB 官方 Java 驱动
不依赖 Spring Data 抽象层
最灵活但也最底层
需要手动处理更多细节
示例代码:
@Autowired
private MongoClient mongoClient;
public void insertUser(User user) {
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("users");
collection.insertOne(new Document("name", user.getName())
.append("age", user.getAge()));
}
五、主要区别对比
方式 | 编程模型 | 抽象级别 | 适用场景 | 学习曲线 |
---|---|---|---|---|
MongoTemplate | 命令式 | 中等 | 复杂查询/操作 | 中等 |
MongoRepository | 命令式 | 高 | 简单 CRUD | 低 |
ReactiveMongoTemplate | 响应式 | 中等 | 响应式复杂操作 | 较高 |
ReactiveMongoRepository | 响应式 | 高 | 响应式简单 CRUD | 中等 |
原生驱动 | 命令式 | 低 | 需要直接控制 | 高 |
六、选择建议
简单 CRUD:优先考虑 MongoRepository/ReactiveMongoRepository
复杂查询/聚合:使用 MongoTemplate/ReactiveMongoTemplate
响应式应用:选择 Reactive 版本
需要直接控制底层:使用原生驱动。