类型错误:如果没有指定方向,key_or_list 必须是 list 的一个实例

Rit*_*itz 6 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)
Run Code Online (Sandbox Code Playgroud)

错误:-

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
Run Code Online (Sandbox Code Playgroud)

Dim*_*tri 13

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

  • 这是不正确的。sort 接受字段名称和方向(升序或降序)。上面的“:”应该替换为“,”,结果是 `collection.find().sort("_id", -1)` 或 `collection.find().sort("_id", pymongo.ASCENDING) ` (3认同)

小智 6

仅尝试:

collection.find().sort("_id", -1)
Run Code Online (Sandbox Code Playgroud)