SpringBoot使用mongodb查询时只返回某些字段值

springboot使用mongodb查询的时候会遇到服务器出口带宽压力大的情况,原因可能是查询mongodb的时候把整个对象给拖下来了,事实上我们只需要其中的某些字段,多余的字段返回的话会给小水管的带宽加上压力,也就是说我们的mongodb查询时只需要返回某些字段。

看了很多人的各种文章感觉要么是哪里抄袭的要么是哪里拷贝的,根本不靠谱,自己去查询了下官方文档,实现方法很简单:直接使用mongoTemplate来查询,只返回主键,name,status字段。(主键是默认返回的)

Query query = new Query();
query.addCriteria(Criteria.where("status").is(3));
query.skip(skipNumber);
query.limit(pageSize);
query.fields().include("name").include("status");
return mongoTemplate.find(query, CompanyInformation.class);

 网上流传比较多的另外一种方法:

​
        BasicDBObject dbObject = new BasicDBObject();
        dbObject.put("id", "123");
        dbObject.put("name", "haha");
        //指定返回的字段
        BasicDBObject fieldsObject = new BasicDBObject();
        fieldsObject.put("id", true);
        fieldsObject.put("name", true);
        fieldsObject.put("age", true);
        Query query = new BasicQuery(dbObject.toJson(), fieldsObject.toJson());
        List<JavaEntity> list= mongoTemplate.find(query, JavaEntity.class, "collectionName");
 
​

 

### 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) 功能开发当中去。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值