python操作mongodb之八地理索引空间数据
from pymongo import MongoClient, GEO2D #使用geo_example库 db = MongoClient('192.168.30.252',27017).geo_example #创建索引在places上的loc列 db.places.create_index([("loc",GEO2D)]) #插入坐标数据 result = db.places.insert_many([{"loc": [2, 5]},{"loc":[30, 5]},{"loc": [1, 2]},{"loc": [4, 4]}]) #查询离[3,6]最近的坐标 for doc in db.places.find({"loc": {"$near": [3, 6]}}).limit(3): repr(doc) from bson.son import SON #增加最大距离 query = {"loc": SON([("$near", [3, 6]), ("$maxDistance", 2)])} #在(2,2) (5,6)lower-left and upper-right query = {"loc": {"$within": {"$box": [[2, 2], [5, 6]]}}} for doc in db.places.find(query).sort('_id'): repr(doc) #在半径为6的圆内 query = {"loc": {"$within": {"$center": [[0, 0], 6]}}} for doc in db.places.find(query).sort('_id'): repr(doc) from bson.son import SON db.command(SON([('geoNear', 'places'), ('near', [1, 2])]))