Using pymongo to sort the results by datetime

Using pymongo to sort the results by datetime

  • 1. Do not sort results:
temp = datetime.datetime(2017, 9, 10, 0, 0)
for i in self.collection.find({"symbol":"SZ300001","timestamp":{'$gte':temp}})
{'_id': ObjectId('5aacc018af39d090785dc948'), 'symbol': 'SZ300001', 'timestamp': datetime.datetime(2017, 9, 18, 0, 0), 'avg_price': None, 'current': 17.79, 'volume': 12314795}, 
{'_id': ObjectId('5aacc018af39d090785dc949'), 'symbol': 'SZ300001', 'timestamp': datetime.datetime(2017, 9, 27, 0, 0), 'avg_price': None, 'current': 17.27, 'volume': 13054714}, 
{'_id': ObjectId('5aacc018af39d090785dc94a'), 'symbol': 'SZ300001', 'timestamp': datetime.datetime(2017, 9, 20, 0, 0), 'avg_price': None, 'current': 17.35, 'volume': 9578619}, 
{'_id': ObjectId('5aacc018af39d090785dc94b'), 'symbol': 'SZ300001', 'timestamp': datetime.datetime(2017, 9, 14, 0, 0), 'avg_price': None, 'current': 17.71, 'volume': 19168838},
  • 2. Sort query:
temp = datetime.datetime(2017, 9, 18, 0, 0)
for i in self.collection.find({"symbol":"SZ300001","timestamp":{'$gte':temp}}).sort([{"timestamp":1}])

The error is reported as follows:

Traceback (most recent call last):
  File "Select.py", line 85, in <module>
    a = sm.main()
  File "Select.py", line 77, in main
    data = self.find_mongo()
  File "Select.py", line 28, in find_mongo
    for i in self.collection.find({"symbol":self.symbol,"timestamp":{'$gte':temp}}).sort([{"timestamp":1}]):
  File "/Users/chenwei/.local/share/virtualenvs/work-1VtIgGs7/lib/python3.6/site-packages/pymongo/cursor.py", line 704, in sort
    self.__ordering = helpers._index_document(keys)
  File "/Users/chenwei/.local/share/virtualenvs/work-1VtIgGs7/lib/python3.6/site-packages/pymongo/helpers.py", line 72, in _index_document
    for (key, value) in index_list:
ValueError: not enough values to unpack (expected 2, got 1)

Obviously, there is a problem with the helpers.py +72 line. Enter and check
Change for (key, value) in index list: to for (key, value) in index list [0]. Items():

Solve the problem successfully!
Some people may say that my pymongo's sort() statement has problems. However, after a small compilation of all kinds of stepping holes and finding no results, we can only look at the source code. There are other schemes that are better. I hope it will help the little partner who is stepping on the hole!

Posted on Wed, 01 Apr 2020 12:12:33 -0700 by ccjob2