'Convert SQL statement to PyMongo

I have the following SQL query which I am trying to convert to PyMongo

SELECT sum(pop), city
FROM mongo.test.zips
WHERE state = ‘CO’ and pop > 1000
GROUP BY city
ORDER BY sum(pop) DESC

I am struggling with the ORDER BY statement and would appreciate any help on how to implement this in PyMongo. I have experimented with the aggregate function but can't reproduce the SQL.

This is what I have so far :

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["test"]
mycol = mydb["zips"]
myquery = { "state": "CO" , "pop" : { "$gt" : 1000 }}
mydoc = mycol.find(myquery).sort("pop", -1)
for x in mydoc:
  print(x)

Thanks for any help !



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source