在 Mongo Shell 執行 db.posts.find() 直接顯示文檔,但在 Python 下 mycol.find() 卻返回 <pymongo.cursor.Cursor object at 0x...>,且 for post in mycol.find() 還報 SyntaxError。這是因為交互式 Shell 自動迭代 Cursor,而腳本需手動迭代。
| 環境 | 指令 | 結果 |
|---|---|---|
| Mongo Shell | db.posts.find() | 自動迭代並美化輸出前 20 筆 |
| Python REPL | mycol.find() | 返回 Cursor 物件(惰性評估) |
| Python REPL | for post in mycol.find() | SyntaxError(REPL 需完整區塊) |
| Python 腳本 | for post in mycol.find(): print(post) | 正常遍歷輸出 |
for doc in mycol.find({"author": "jim"}):
print(doc["title"], doc["tags"])
docs = list(mycol.find({"tags": "python"}))
print(docs[0]["title"])
doc = mycol.find_one({"_id": ObjectId("...")})
if doc:
print(doc["text"])
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 會幫你迭代,腳本要自己迭代。