【问题标题】:TypeError: if no direction is specified, key_or_list must be an instance of listTypeError: 如果没有指定方向,key_or_list 必须是 list 的一个实例
【发布时间】:2020-01-06 18:32:44
【问题描述】:

我在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

【问题讨论】:

标签: python pymongo


【解决方案1】:

collection.find().sort("_id",-1) 应该这样做 - 没有“{}”。 你也可以试试: collection.find().sort("_id", pymongo.ASCENDING)使用python时

【讨论】:

  • 这是不正确的。 sort 接受字段名称和方向,ASCENDING 或 DESCENDING。您的“:”上方应替换为“,”,导致collection.find().sort("_id", -1)collection.find().sort("_id", pymongo.ASCENDING)
【解决方案2】:

尝试一下:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多