win安装mongodb
MongDB版本
- 创建
mongo.conf
配置文件,内容如下
dbpath=D:\mongo\datalogpath=D:\mongo\log\mongo.loglogappend=truejournal=truequiet=trueport=27017复制代码
- 启动MongDb
D:\programs\mongodb-win32-x86_64-2008plus-ssl-3.6.12\bin>mongod.exe --config D:\mongo\config\mongo.conf复制代码
JPA添加数据和使用GEO索引查询中心点附近数据
org.springframework.boot spring-boot-starter-data-mongodb 复制代码 org.mongodb mongo-java-driver 3.4.3
##mongo配置spring: data: mongodb: host: 127.0.0.1 port: 27017 database: test复制代码
实体类
import lombok.Data;import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;import org.springframework.data.mongodb.core.index.GeoSpatialIndexed;import org.springframework.data.mongodb.core.index.Indexed;import org.springframework.data.mongodb.core.mapping.Document;@Data@Document(collection = "bikes")public class Bike { @Id private String id; private int status; @Indexed private long bikeNo; // 空间球面索引 @GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE) private double[] location;}复制代码
import com.niubike.niubike.entity.Bike;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.geo.GeoResult;import org.springframework.data.geo.GeoResults;import org.springframework.data.geo.Metrics;import org.springframework.data.mongodb.core.MongoTemplate;import org.springframework.data.mongodb.core.query.Criteria;import org.springframework.data.mongodb.core.query.NearQuery;import org.springframework.data.mongodb.core.query.Query;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestControllerpublic class BikeController { @Autowired private MongoTemplate mongoTemplate; @PostMapping("/addBike") public String save(@RequestBody Bike bike) { bike.setBikeNo(System.currentTimeMillis()); bike.setStatus(0); mongoTemplate.insert(bike); return "1"; } /** * 根据当前经纬度查找附近单车 * @return */ @PostMapping("/findNearBike") public List> findNearBike(double longitude, double latitude) { NearQuery nearQuery = NearQuery .near(longitude, latitude) .maxDistance(0.2, Metrics.KILOMETERS) .query(new Query(Criteria.where("status").is(0)).limit(20)); GeoResults geoResults = mongoTemplate.geoNear(nearQuery, Bike.class); return geoResults.getContent(); }}复制代码
效果
查询附近单车数据代码对于高版本的MongoDB不适用。