使用pymongo对查询出来的结果按照datetime时间排序
- 1、不排序结果:
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、排序查询:
temp = datetime.datetime(2017, 9, 18, 0, 0)
for i in self.collection.find({"symbol":"SZ300001","timestamp":{'$gte':temp}}).sort([{"timestamp":1}])
报错如下:
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)
很明显是helpers.py +72
行有问题,进入并查看
将for (key,value) in index_list:
改为for (key,value) in index_list[0].items():
成功解决问题!
可能有人会说,是我的pymongo
的sort()
语句有问题,但是,经过小编各种踩坑,发现无果,才看源码,有其他方案更好,发出来希望对正在踩坑的小伙伴有帮助!