在pymong中使用Find

2024-05-14 21:48:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想对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)

但是,它显示出这样的错误:

^{pr2}$

如何解决这个问题? 谢谢您! 对不起,我的英语成绩不好。在


Tags: importclientlocalhostdbmongodbfindcursormongoclient
1条回答
网友
1楼 · 发布于 2024-05-14 21:48:19

与mongoshell不同,pymongo将key和{}作为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/cursor.html?highlight=sort#pymongo.cursor.Cursor.sort

你可以在这里找到ASCENDINGDESCENDING常量https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.ASCENDING

顺便说一句(与你原来的问题无关) db['produk']实际上是一个集合,而不是一个游标,所以最好将其称为collection,而不是cursor。 Cursor是find()返回的内容

相关问题 更多 >

    热门问题