Pymongo 试验

首先将 geojson 数据导入到 MongoDB 中,具体操作参考如下

需要使用两条命令:

1
2
jq --compact-output ".features" input.geojson > output.geojson
mongoimport --db dbname -c collectionname --file "output.geojson" --jsonArray

通过上述命令,我导入了 nyu yellow taxi 的 json 数据。该 json 数据是经过后期处理的,格式如下:

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
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"place": "nyu"
},
"geometry": {
"type": "Point",
"coordinates": [
-73.98268127441406,
40.731311798095696
]
}
},
{
"type": "Feature",
"properties": {
"place": "nyu"
},
"geometry": {
"type": "Point",
"coordinates": [
-73.99224853515625,
40.74908065795898
]
}
},
...

比如我想要获得 nyu 南边一个圆里面的所有 taxi 信息。

find 请求如下:

1
{geometry: {$geoWithin: { $centerSphere: [ [ -74.0093912556225, 40.7094698471372 ], 0.00008092516322998259 ]}}}

而改写到 pymongo 里面则是:

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
import pymongo
import pprint as pp
import json
# Replace XXXX with your connection URI from the Atlas UI

# mongodb:// is the protocol definition
# localhost:27017 is the server we are connecting to
# /myproject is the database we wish to connect to

url = 'mongodb://localhost:27017/m201'
client = pymongo.MongoClient(url)
taxi = client['m201']['nyu_taxi']

query = {
"geometry": {
"$geoWithin": {
"$centerSphere": [
[ -74.0093912556225, 40.7094698471372 ],
0.00008092516322998259
]
}
}
}
projection = {"_id":0}

points = {}
points['type'] = 'FeatureCollection'
points['features'] = []

for t in taxi.find(query,projection):
# print(t)
points['features'].append(t)

pp.pprint(points)

# save as geojson format
with open('./filter_nyu_taxi.json', 'w') as outfile:
json.dump(points,outfile, indent=4)
0%