python TypeError:如果未指定方向,key_or_list必须是list的示例

x33g5p2x  于 2023-01-24  发布在  Python
关注(0)|答案(3)|浏览(123)

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

hec6srdp1#

尝试仅使用:

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

vyswwuz22#

collection.find().sort("_id",-1)应该可以执行此操作-不使用“{}”。您还可以尝试:collection.find().sort("_id", pymongo.ASCENDING)当使用python时

6yjfywim

6yjfywim3#

PyMongo的.sort()函数提到了语法-(self:cursor, key_or_list, direction)
PyMongo提供了方向变量pymongo.Ascending和pymongo. DESCENDING。分离.find().sort()函数对我很有效。
与您类似的数据库设置-我尝试了以下代码块

degree_collection = db["degrees"]
degrees = degree_collection.find({}, {"degree_id": 1, "degree": 1, "_id": 0})
degrees = degrees.sort("degree_id", pymongo.ASCENDING)

这对我很有效。
PS:这段代码的集成版本,即使用具有相同属性的find().sort()格式对我来说不起作用。

相关问题