【发布时间】:2019-07-11 05:20:51
【问题描述】:
在使用 insert_many 时,我在使用 pymongo 持久化文档时遇到了一些问题。
我正在将 dicts 列表移交给insert_many,它可以在执行插入的同一脚本中正常工作。脚本完成后就不那么简单了。
def row_to_doc(row):
rowdict = row.to_dict()
for key in rowdict:
val = rowdict[key]
if type(val) == float or type(val) == np.float64:
if np.isnan(val):
# If we want a SQL style document collection
rowdict[key] = None
# If we want a NoSQL style document collection
# del rowdict[key]
return rowdict
def dataframe_to_collection(df):
n = len(df)
doc_list = []
for k in range(n):
doc_list.append(row_to_doc(df.iloc[k]))
return doc_list
def get_mongodb_client(host="localhost", port=27017):
return MongoClient(host, port)
def create_collection(client):
db = client["material"]
return db["master-data"]
def add_docs_to_mongo(collection, doc_list):
collection.insert_many(doc_list)
def main():
client = get_mongodb_client()
csv_fname = "some_csv_fname.csv"
df = get_clean_csv(csv_fname)
doc_list = dataframe_to_collection(df)
collection = create_collection(client)
add_docs_to_mongo(collection, doc_list)
test_doc = collection.find_one({"MATERIAL": "000000000000000001"})
当我打开另一个 python REPL 并开始使用 collection.find_one({"MATERIAL": "000000000000000001"}) 或 collection.count_documents({}) 查看 client.material.master_data 集合时,find_one 得到 None,count_documents 得到 0。
我需要调用一些方法将数据保存到磁盘吗? db.collection.save() 在 mongo 客户端 API 听起来 像我需要的,但它只是插入我已阅读的文档的另一种方式。任何帮助将不胜感激。
【问题讨论】:
-
我退回到 [collection.insert_one(doc) for doc in doc_list]。仍然没有坚持。
标签: pymongo