Search code examples
pythonmongodbpymongo

Using Find in pymongo


I want to use .find() like this for mongoDB in Python :

import pymongo

client = pymongo.MongoClient('mongodb://localhost:27000')
db = client['responsi']
cursor = db['produk']

for x in cursor.find({"pricing.pct_savings":{"$gt":25}}).sort({"pricing.pct_savings":-1}):
    print(x)

But, it showing error like this :

Traceback (most recent call last):
  File "Find.py", line 7, in <module>
    for x in cursor.find({"pricing.pct_savings":{"$gt":25}}).sort({"pricing.pct_savings":-1}):
  File "G:\PROGRAM FILES\Python\lib\site-packages\pymongo\cursor.py", line 708, in sort
    keys = helpers._index_list(key_or_list, direction)
  File "G:\PROGRAM FILES\Python\lib\site-packages\pymongo\helpers.py", line 69, 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

How to solved this problem? Thank you! Sorry, I have bad score in english.


Solution

  • As opposed to the mongo shell, pymongo takes key and direction as the arguments to the sort method (or list, but that's another form that is not relevant to you currently, I'll show it too)
    So your query should actually be cursor.find({"pricing.pct_savings":{"$gt":25}}).sort("pricing.pct_savings", pymongo.DESCENDING)

    The other form gets a list of tuples of field name and the direction, and allows you to sort by multiple fields, for example collection.find().sort([('my_field_1',pymongo.DESCENDING), ('my_field_2',pymongo.ASCENDING)])

    See the relevant documentation here https://api.mongodb.com/python/current/api/pymongo/cursor.html?highlight=sort#pymongo.cursor.Cursor.sort

    You can find the ASCENDING and DESCENDING constants here https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.ASCENDING

    BTW (not related to your original question) db['produk'] is actually a collection, not a cursor, so it would be better if you would call it collection, and not cursor. Cursor is what find() returns