簡體   English   中英

在 pymongo 中使用 Find

[英]Using Find in pymongo

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

如何解決這個問題? 謝謝,對不起。 我英語成績不好

與 mongo shell 不同,pymongo 將keydirection作為 arguments 的排序方法(或列表,但這是目前與您無關的另一種形式,我也會展示它)
所以你的查詢實際上應該是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)])

See the relevant documentation here 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']實際上是一個集合,而不是 cursor,因此最好將其稱為集合,而不是 cursor。 Cursor 是find()返回的

應該只有這個結構

from bson import ObjectId
id = '375g68h97b680jf78j'
data = cursor.find_one_and_delete({'_id': ObjectId(id)})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM