我想在Python的mongoDB中使用.find()
这样的>
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)
但是,它显示了这样的错误:
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
如何解决这个问题? 谢谢! 抱歉,我的英语成绩不好。
答案 0 :(得分:0)
与mongo shell相对,pymongo将key
和direction
作为sort方法(或列表)的参数,但这是当前与您无关的另一种形式也一样)
因此,您的查询实际上应该是cursor.find({"pricing.pct_savings":{"$gt":25}}).sort("pricing.pct_savings", pymongo.DESCENDING)
另一种形式获取字段名称和方向的元组列表,并允许您按多个字段进行排序,例如collection.find().sort([('my_field_1',pymongo.DESCENDING), ('my_field_2',pymongo.ASCENDING)])
您可以在https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.ASCENDING处找到ASCENDING
和DESCENDING
常量
顺便说一句(与您的原始问题无关)
db['produk']
实际上是一个集合,而不是游标,因此最好将其称为集合而不是游标。
find()
返回的光标是