5

mongodb geoNear 使用记录 - SegmentFault 思否

 2 years ago
source link: https://segmentfault.com/a/1190000040284843
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

mongodb geoNear 使用记录

需要,查询一个坐标点的附近位置

可以用数组或者geojson的形式

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

GeoJSON

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

先列出经度,然后再列出纬度

比如 loc 字段

  {
    "city": "北京市",
    "geo_id": 565932,
    "geo_name": "万柳园(长春堂药店)",
    "lat": 39.850201868495773283,
    "lng": 116.33426020654366084,
    "loc": "[116.33426020654366084,39.850201868495773283]",
    "status": 0
 }

创建 2dsphere 索引

2dsphere索引支持查询球面几何实体对象

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

pymongo查询例子

        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 查询的坐标点
  • maxDistance 最大距离
  • query 过滤条件

links


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK