![](/img/trans.png)
[英]How to get sum of a particular field of a collection in MongoDB collection using PyMongo?
[英]pymongo: how to access MongoDB collection by name as string?
我想將csv文件寫入mongoDB。
我想將集合的名稱與csv文件的名稱相同。
以下是我嘗試過的代碼。 這會將集合名稱寫為“集合”。
from pymongo import MongoClient
import pandas as pd
import os
#get all csv files from the directory
dir_path = r'C:\Users\USER\Desktop\project'
output_files = [file for file in os.listdir(dir_path) if file.endswith(".csv")]
client = MongoClient()
db = client.senci
for file in output_files:
collection = file[-4]
df = pd.read_csv(file)
records_ = df.to_dict(orient = 'records')
result = db.collection.insert_many(records_ )
您需要使用db.getCollection() :
db.get_collection(collection).insert_many(records_ )
從文檔:
返回在功能上等效於使用
db.<collectionName>
的集合或視圖對象db.<collectionName>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.