首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

PyMongo find() 返回 Cursor 而非列表?正確遍歷與資料取回姿勢

     編輯:程式設計綜合問答

在 Mongo Shell 執行 db.posts.find() 直接顯示文檔,但在 Python 下 mycol.find() 卻返回 <pymongo.cursor.Cursor object at 0x...>,且 for post in mycol.find() 還報 SyntaxError。這是因為交互式 Shell 自動迭代 Cursor,而腳本需手動迭代。

現象對照

環境指令結果
Mongo Shelldb.posts.find()自動迭代並美化輸出前 20 筆
Python REPLmycol.find()返回 Cursor 物件(惰性評估)
Python REPLfor post in mycol.find()SyntaxError(REPL 需完整區塊)
Python 腳本for post in mycol.find(): print(post)正常遍歷輸出

正確用法:三種遍歷姿勢

1. 直接 for 迴圈(最常用、記憶體友善)

for doc in mycol.find({"author": "jim"}):
    print(doc["title"], doc["tags"])

2. 轉列表(小資料集、需隨機存取)

docs = list(mycol.find({"tags": "python"}))
print(docs[0]["title"])

3. 單筆查詢用 find_one()

doc = mycol.find_one({"_id": ObjectId("...")})
if doc:
    print(doc["text"])

為什麼 REPL 下 for 會 SyntaxError?

Python REPL(>>>)不支援多行區塊語句。輸入 for ... 後按 Enter,REPL 以為語句結束,實際缺少冒號與縮排區塊。解決:

  • 寫 .py 檔案再執行
  • 或用 ipython / jupyter 支援多行
  • 或單行寫法:for doc in mycol.find(): print(doc)(不建議,可讀性差)

進階:投影、排序、分頁

# 只取需要欄位(投影)
cursor = mycol.find({}, {"title": 1, "author": 1, "_id": 0})

# 排序 + 分頁
cursor = mycol.find().sort("likes", -1).skip(10).limit(5)

# 計數(不拉取資料)
count = mycol.count_documents({"author": "mike"})

總結

find() 返回 Cursor 游標,而非列表。Cursor 是惰性迭代器,只有在 for、list()、next() 時才真正向 MongoDB 發送 getMore 請求。記住:Shell 會幫你迭代,腳本要自己迭代。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved