Mongodb geonear usage record

Time:2021-9-11

If necessary, query the location near a coordinate point

data format

It can be in the form of array or geojson

<field>: [ <x>, <y> ]
<field>: [<longitude>, <latitude> ]

GeoJSON

location: {
      type: "Point",
      coordinates: [-73.856077, 40.848447]
}

List longitude first, then latitude

For example, LOC field

{
    "City": "Beijing",
    "geo_id": 565932,
    "Geo_name": "wanliuyuan (Changchun Tang drugstore)",
    "lat": 39.850201868495773283,
    "lng": 116.33426020654366084,
    "loc": "[116.33426020654366084,39.850201868495773283]",
    "status": 0
 }

Indexes

Create a 2dsphere index

The 2dsphere index supports querying spherical geometric entity objects

db.collection.createIndex( { <location field> : "2dsphere" } )

Pymongo query example

        lng = geo['lng']
        lat = geo['lat']
        result = geos_collection.aggregate([
            {"$geoNear": { 
                "near": { 
                    "type": "Point",
                    "coordinates": [lng, lat] }, 
                    "distanceField": "distance", 
                    "maxDistance": 2000, 
                    "query": {"status": -1}, 
                    "spherical": True }
            },
            {"$limit": 10}
        ])

mongodb shell

db.o2o_geos.aggregate([
   {
     $geoNear: {
        near: { type: "Point", coordinates: [120.13606048541625171, 30.29447292933346958 ] },
        distanceField: "distance",
        maxDistance: 2000,
        query: { status: -1 },
        spherical: true
     }
   }
])
  • Coordinates the coordinate point of the query
  • Maxdistance maximum distance
  • Query filter criteria

links

Recommended Today

“Self test” stay up late to summarize 50 Vue knowledge points, all of which will make you God!!!

preface Hello everyone, I’m Lin Sanxin. A lot of things have happened these days (I won’t say what’s specific). These things have scared me to treasure my collection these yearsVue knowledge pointsI took out my notes and tried my best to recall them. Finally, I realized these 50Knowledge points(let’s not be too vulgar. It’s not […]