mongodb gis查询

官网地址:

https://www.mongodb.com/docs/manual/reference/operator/query-geospatial/

 

git demo

https://github.com/mongodb/docs-java/blob/master/source/includes/fundamentals/code-snippets/Geo.java

 

数据准备:

db.collection.createIndex( {loc  : "2dsphere" } )

db.places.insertMany( [
{
loc : { type: "Point", coordinates: [ -73.97, 40.77 ] },
name: "Central Park",
category : "Parks"
},
{
loc : { type: "Point", coordinates: [ -73.88, 40.78 ] },
name: "La Guardia Airport",
category : "Airport"
}
] )

db.places.find( { loc :
{ $geoWithin :
{ $geometry :
{ type : "Polygon" ,
coordinates : [ [
[ 0 , 0 ] ,
[ 3 , 6 ] ,
[ 6 , 1 ] ,
[ 0 , 0 ]
] ]
} } } } )

 

my demo

MongoCollection<Document> coll = MongoUtils.getConnection().getDatabase("db_name").getCollection("places");

Polygon polygon = new Polygon(Arrays.asList(new Position(0, 0),
new Position(3, 6),
new Position(6, 1),
new Position(0, 0)));
Bson match = Filters.geoWithin("loc", polygon);
MongoCursor<Document> iterator = coll.find(match).iterator();
while (iterator.hasNext()){
System.out.println(iterator.next().toJson());
}

 

posted @ 2023-05-08 17:41  空虚公子  阅读(34)  评论(0编辑  收藏  举报