Py学习  »  MongoDB

为什么我的代码不能通过pymongo自动将数据从dataframe存储到mongodb?

Helix Herry • 4 年前 • 378 次点击  

我正在通过API从问答网站上抓取数据,我想自动存储数据。 通常,工作流是获取主题ID并获取此主题的所有QA ID,然后我想将每个QA存储为mongoDB集合。 为了测试我的设计,我写了如下:

def df2bson(df):#transfer the dataframe to bson format
    data = json.loads(df.T.to_json()).values()
    return data
def df2mongo(self,topic_id):#store in the MongoDB
    bson_data = df2bson(df)
    client = MongoClient()
    mydb = client["zhihu_wenchuan"]
    collection = mydb.topic_id
    return collection

def get_topics(topic_id):#the function to get the demo topic
num = 1
row = []
for que in topic.unanswered_questions:
     if num< topic.questions_count:
            a = get_questions(que)
            row.append(a)
            num+=1
            if num%10==0:
                flushPrint(num/10)
 #           time.sleep(random.randint(0,1))
df = pd.DataFrame(row)
data = df2bson(df)
col = df2mongo(data,topic_id) #maybe here is the problem,but I don't know how to fix it
return col

我可以成功获取主题数据并将其存储为df,我可以通过逐行编码(手动更改集合名称)成功地将它们存储到MongoDB,但我不能通过上面的代码将数据存储到MongoDB(自动将id写入集合名称)。

问题是,当我想得到数千个qa时,我不能写出它们的每个集合名,我需要使用for循环和函数来完成它? 如何调整代码?请~~

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52065
 
378 次点击