I would like to create a query to calculate the average geographical position of all tree species in MongoDb.My code is here:
from pymongo import MongoClient
from utils import get_my_password, get_my_username
from pprint import pprint
client = MongoClient(
host='127.0.0.1',
port=27017,
username=get_my_username(),
password=get_my_password(),
authSource='admin'
)
db = client['paris']
col = db['trees']
pprint(col.find_one())
{'_id': ObjectId('5f3276d8c22f704983b3f681'),
'adresse': 'JARDIN DU CHAMP DE MARS / C04',
'arrondissement': 'PARIS 7E ARRDT',
'circonferenceencm': 115.0,
'domanialite': 'Jardin',
'espece': 'hippocastanum',
'genre': 'Aesculus',
'geo_point_2d': [48.8561906007, 2.29586827747],
'hauteurenm': 11.0,
'idbase': 107224.0,
'idemplacement': 'P0040937',
'libellefrancais': 'Marronnier',
'remarquable': '0',
'stadedeveloppement': 'A',
'typeemplacement': 'Arbre'}
I tryed to do it with next lines:
cursor = col.aggregate([
{'$match': {first: $arrayElemAt: [ "$geo_point_2d", 0 ]},
{last: $arrayElemAt: [ "$geo_point_2d", 1 ]}},
{'$group': {'_id': '$espece', 'GeoMeanTreeSpieces': {'$avg': 1}}},
{'$project': {'_id': 0, 'espece': '$_id', 'GeoMeanTreeSpieces': '$GeoMeanTreeSpieces'}}
])
print(list(cursor))
It doesn’t work. I need more and more practices. I got this error:
File "<ipython-input-9-2a108c75c8c4>", line 20
{'$match': {first: $arrayElemAt: [ "$geo_point_2d", 0 ]},
^
SyntaxError: invalid syntax
Could you help me please to find a solution please?
Best regards
2
Answers
I found out the SOLUTION of this task:
And the answer:
I was not clear when I ask about it. Thank you for help. Best regards
If I understand correctly (this is not the actual GeoMeanTreeSpieces, the name is confusing):
See how it works on the playground example