London, UK
Software Engineer
Biker

I'm trying to write more. Maybe this will help?

Geospatial queries with MongoDB

Geospatial queries with MongoDB

I'm currently playing with MongoDB and its geospatial queries. It’s pretty interesting so far, so I just thought I'd write something up to show how I'm using it with PyMongo!

Firstly, the obvious pip install pymongo is needed. We will need a mongo client first, which is easy enough

from pymongo import MongoClient

client = MongoClient()
Import Pymongo and create a client

It’s pretty neat - by default, MongoClient will connect to mongodb://localhost:27017.

You might want to do something like this instead though

url = os.environ.get("MONGO_URL", "mongodb://localhost:27017")
client = MongoClient(url)
Create a client, but in a configurable way

We're going to want to create a MongoDB index on a document field to allow the geospatial magic to work. We will be creating a 2dsphere index.

from pymongo import MongoClient, GEOSPHERE, DESCENDING

client = MongoClient()
db = client.foo
db.bar.create_index([("location", GEOSPHERE)])
Create an index on the location field

Now all that is needed is to insert a document and run a query :) We'll insert a document that just has a location field

db.bar.insert_one({
	“location”: {
		"coordinates" : [ 
			51.4982563, 
			-0.0861183
    		],
    		"type" : "Point"
	}
})
Add something :O

The location field needs to be GeoJSON, which is a JSON standard for representing geographic features. It makes querying for documents super easy!

db.bar.find({
	"location": {
		"$near": {
			"$geometry": {"type": "Point", "coordinates": [LAT, LONG]},
			"$maxDistance": range,
		}
	}
})
Testing it out