TypeError:如果未指定方向,Key_or_List必须是List的实例

2022-03-14 00:00:00 python pymongo

问题描述

我在collection.find({}).sort({"_id":-1})行遇到错误,如何在MongoDB中对文档集合进行排序?

count = 1
cursor = collection.find({}).sort({"_id":-1})
for document in cursor:
    if count !=100:
        logger.info('COUNT %s'%count)
        logger.info('document %s'%document)
    else:
        logger.info('Exiting...')
        sys.exit(0)

错误:-

Traceback (most recent call last):
  File "ibait_data_integrity.py", line 79, in <module>
    main()
  File "ibait_data_integrity.py", line 66, in main
    cursor = collection.find({}).sort({"_id":-1})
  File "/Library/Python/2.7/site-packages/pymongo/cursor.py", line 703, in sort
    keys = helpers._index_list(key_or_list, direction)
  File "/Library/Python/2.7/site-packages/pymongo/helpers.py", line 52, in _index_list
    raise TypeError("if no direction is specified, "
TypeError: if no direction is specified, key_or_list must be an instance of list

解决方案

仅尝试:

collection.find().sort("_id", -1)

相关文章