我想使用pymongo中的回调函数在mongodb中对文档进行迭代,但在foreach中出现了错误。

问题描述 投票:1回答:1

我想使用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: invalid syntax(无效语法)

python pymongo
1个回答
0
投票

做以下修改,应该就可以了。问题是你试图用python使用Mongo shell命令。

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,请使用 艋舺出口

© www.soinside.com 2019 - 2024. All rights reserved.