-
Notifications
You must be signed in to change notification settings - Fork 0
/
2dsphere index.py
47 lines (40 loc) · 1.24 KB
/
2dsphere index.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Create a collection called "restaurants" and insert documents representing restaurants with fields like "name", "location", and "cuisine".
# Create a 2dsphere index on the "location" field.
# Write a query to find all restaurants within a certain distance from a given latitude and longitude.
import pymongo
from pprint import pprint
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['test']
restaurants = db.restaurants
restaurants_data = [
{
'name': 'Restaurant A',
'location': {
'type': 'Point',
'coordinates': [40, 69]
},
'cuisine': 'Italian'
},
{
'name': 'Restaurant B',
'location': {
'type': 'Point',
'coordinates': [8, 42]
},
'cuisine': 'Mexican'
},
{
'name': 'Restaurant C',
'location': {
'type': 'Point',
'coordinates': [90,88]
},
'cuisine': 'Chinese'
}
]
# restaurants.insert_many(restaurants_data)
restaurants.create_index([('location',pymongo.GEOSPHERE)])
query = {'location':{'$near':{'$geometry':{'type':'Point','coordinates':[8,42]}, '$maxDistance':5000}}}
for restaurant in restaurants.find(query):
pprint(restaurant)