Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: if no direction is specified, key_or_list must be an instance of list

Tags:

python

pymongo

I am running into error at line collection.find({}).sort({"_id":-1}),how do I sort a collection of documents in 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)

Error:-

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
like image 744
Ritz Avatar asked Sep 03 '19 20:09

Ritz


2 Answers

try with just:

collection.find().sort("_id", -1)
like image 151
david choi Avatar answered Oct 31 '22 17:10

david choi


collection.find().sort("_id",-1) should do it - without the '{}'. you can also try : collection.find().sort("_id", pymongo.ASCENDING) when using python

like image 35
Dimitri Avatar answered Oct 31 '22 18:10

Dimitri