我想使用 pymongo 中的回调函数迭代 mongodb 中的文档,但我在 foreach 中遇到错误



我想使用 pymongo 中的回调函数迭代 mongodb 中的文档,但我在 foreach 中遇到错误:

from pymongo import MongoClient
import pandas as pd
client = MongoClient('localhost', 27017)
db = client['testing']
collection_currency = db['testcol']
getdata=[]
cursor=collection_currency.find().forEach((data)=>{getdata=data})
df=pd.DataFrame(cursor)
df.to_csv("data.csv",index=False)

我收到此错误

cursor=collection_currency.find((.forEach((data(=>{getdata=data}(
^
SyntaxError: 无效语法

进行以下更改,它应该可以工作。问题是你正在尝试将Mongo shell命令与python一起使用。

query = {}
cursor = collection_currency.find(query)
df = pd.DataFrame(list(cursor))

加载一段数据。

n_documents = 1000
skip_documents = 1000
cursor = collection_currency.find(query).skip(skip_documents).limit(n_documents)
df = pd.DataFrame(list(cursor))

要将集合中的数据写入 csv,请使用 mongoexport

最新更新