总结MongoDB采用MongoRepository进行查询

本文介绍了如何在Java中使用MongoRepository进行MongoDB的数据操作,包括查询所有、分页查询、计数、按属性查询、模糊查询、分页模糊查询、返回指定字段等方法的实现,并给出了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java操作MongoDB采用MongoRepository进行条件查询

1)  实体类实现Serializable接口

@Document(collection = "Memo")
public class Memo implements Serializable {}

2) DAO继承MongoRepository<Class<T>,参数类型>, 并定义方法(若MongoRepository自带方法够用,可以不定义新方法)

@Repository
public interface MemoRepository extends MongoRepository<Memo, String> {
    ArrayList<Memo> findByUserId(String userId);
}

3) 将DAO的Repository注入到Service类(Controller)

@Api(description = "备忘录相关接口")
@RestController
public class MemoController {

    private final MemoRepository memoRepository;

    @Autowired
    public MemoController(MemoRepository memoRepository) {
        this.memoRepository = memoRepository;
    }
}


Repository常用条件查询:

1. 查询所有 

findAll();


2. 分页

public Page<T> queryAllByPage (int page, int rows) throws Exception {

pageRequest pr = new pageRequest(page-1, rows);

return memoReponsitory.findAll(pr);

}


3. 查询所有数据的数量

long size =  memoRepository.count();

int count = Integer.valueOf(String.valueOf(size));


4按实体类属性查询

a.先在DAO层定义方法.     

定义方法名的规则:findBy+属性名(首字母大写)

b.在Service中调用该方法


5.根据属性分页

findBy+属性名(参数类型 参数名,Pageable p)

例:Page<Memo> memos = memoRepository.findByQsId(String qsId, Pageable p);

@ApiOperation(value="根据qsId获取备忘录列表", notes="根据用户的qsId获取备忘录列表")
@RequestMapping(value = "/{qsId}/memos", method = RequestMethod.GET)
public ResultData list(
        @RequestHeader("token") String token,
        @ApiParam(required = true, value = "qsId") @PathVariable("qsId") String qsId,
        @RequestParam(defaultValue = "1", name = "page") Integer page,
        @RequestParam(defaultValue = "20", name = "size") Integer size) {

    //验证qsId一致
    UserDto baseUser = userService.getBaseUserByToken(token);
    if (!StringUtils.equals(baseUser.getQsId(), qsId)) {
        throw new ForbiddenException();
    }

    PageRequest pageable = new PageRequest(page-1, size, new Sort(Sort.Direction.DESC, "createAt"));
    Page<Memo> memos = memoRepository.findByQsId(qsId, pageable);
    return ResultData.ok()
            .putDataValue("memos", memos);
}
注:数据库查询分页后,首页默认是第0页,所以当page的默认值为1时,pageRequest的page参数为page-1 


6.根据属性模糊查询

定义方法名的规则:findBy+属性名(首字母大写)+Like(参数类型 参数名);

例:public Memo findByIdLike(String id);


7. 属性模糊查询+分页

a.DAO定义方法:

public Page<T> findByNameLike(String name, Pageable p);

b.Service调用该方法

public List<Memo> queryByNameAndPage(int page, int rows, String name) throws Exception {

PageRequest pr = new PageRequest(page-1, rows);

return memoRepository.findByNameLike(name, pr).getContent()

}


8.所有数据返回指定字段

@Query(value= "{'_id': {'$ne':null}", fields="{'name':1}")

注:value是查询条件,field是指定的返回字段

返回对象的Id自动返回,不用指定

标红区域可用其他MongoDB原子操作命令代替


9.根据属性查询+分页+返回指定字段

@Query(value="{'name':?0}", fields="{'name':1}")

public Page<Person> findByNameLike(String name, Pageable p);

注:?0 是占位符,其中0表示第一个参数,1表示第二个参数....

field中的1 表示该字段(name)要显示,0表示不显示










### Spring Boot 中 MongoDB 的地理空间查询 在 Spring Boot 和 MongoDB 结合使用的场景下,可以通过 MongoDB 提供的 GeoSpatial 查询功能来实现基于地理位置的最近距离查询。以下是详细的说明: #### 1. 配置依赖项 为了支持 MongoDB 地理空间索引和查询,在 `pom.xml` 文件中需引入以下 Maven 依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> ``` 此依赖会自动配置 Spring Data MongoDB 支持。 --- #### 2. 创建实体类并定义地理坐标字段 MongoDB 使用 GeoJSON 格式存储地理信息。因此需要创建一个实体类,并使用 `@GeoSpatialIndexed` 注解标记地理坐标字段。 ```java import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.geo.GeoJsonPoint; import org.springframework.data.mongodb.core.index.GeoSpatialIndexType; import org.springframework.data.mongodb.core.index.GeospatialIndexed; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "locations") public class Location { @Id private String id; private String name; @GeospatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE) private GeoJsonPoint point; // 表示地理坐标的字段 public Location(String name, double longitude, double latitude) { this.name = name; this.point = new GeoJsonPoint(longitude, latitude); } // Getters and Setters } ``` 上述代码中的 `GeoJsonPoint` 是用于表示地理坐标的对象,它接受经度和纬度作为参数[^1]。 --- #### 3. 定义 Repository 接口 通过继承 `MongoRepository` 或者 `ReactiveMongoRepository` 来定义自定义方法以执行地理空间查询。 ```java import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import org.springframework.data.mongodb.spatial.SpatialCriteria; import org.springframework.data.mongodb.spatial.SpatialOperation; import java.util.List; public interface LocationRepository extends MongoRepository<Location, String> { @Query("{ 'point' : { $nearSphere : { $geometry : { type:\"Point\", coordinates:[ ?0 , ?1 ] }, $maxDistance: ?2 } } }") List<Location> findNearestLocations(double longitude, double latitude, int maxDistanceInMeters); } ``` 在此处,`$nearSphere` 操作符被用来找到离指定点最近的位置记录。`$maxDistance` 参数指定了最大可接受的距离(单位为米)。注意这里的 `$geometry` 字段遵循标准 GeoJSON Point 格式。 --- #### 4. 测试服务逻辑 编写测试用的服务层代码调用 repository 方法完成实际业务需求。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class LocationService { @Autowired private LocationRepository locationRepository; public List<Location> getNearbyLocations(double userLongitude, double userLatitude, int radiusInMeter){ return locationRepository.findNearestLocations(userLongitude,userLatitude,radiusInMeter); } } ``` 当用户请求附近地点时,只需提供其当前位置 (经度/纬度),以及希望检索的最大半径即可获得符合条件的结果列表。 --- #### 5. 距离计算注意事项 由于地球表面并非完全平坦,因此通常采用球面几何算法来进行更精确的距离测量。而 MongoDB 内建的支持已经考虑到了这一点,能够返回较为精准的实际物理距离值。 --- #### 总结 以上就是在 Spring Boot 应用程序里利用 MongoDB 实现基于地理位置最邻近查询的一个基本流程介绍。这不仅限于简单的查找周边设施这样的应用场景,还可以扩展到更多复杂的 LBS(Location Based Service) 功能开发当中去。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值