字典到 mongodb 在一个文档中插入所有数据
dictionary to mongodb insert all data in one document
我尝试在 mongodb 中导入一个 CSV 文件,但使用我的代码,它只在一个文档中插入所有内容:
file_path = tk.filedialog.askopenfilename()
mongo_client = MongoClient()
db = mongo_client.football
file_path2 = file_path + ".json"
df = pd.read_csv(file_path) # loading csv file
df.to_json(file_path2) # saving to json file
with open(file_path2) as f:
file_data = json.load(f)
db.joueurs.insert_many([file_data])
我想将它们插入到不同的文档中。
这是一种读取 CSV 并将数据加载到 MongoDB 集合中的方法。假设文件中的数据如下:
col1,col2
a,1
b,2
以下 Python 和 PyMongo 代码将在集合中创建两个文档。
data = []
file_name = "some.csv"
with open(file_name, newline='') as csvfile:
reader = csv.DictReader(csvfile) # using Python's csv module
for row in reader:
data.append(row)
result = collection.insert_many(data)
集合中生成的文档:
{ "_id" : ObjectId("626fc502c9bbf326c869f434"), "col1" : "a", " col2" : "1" }
{ "_id" : ObjectId("626fc502c9bbf326c869f435"), "col1" : "b", " col2" : "2" }
我尝试在 mongodb 中导入一个 CSV 文件,但使用我的代码,它只在一个文档中插入所有内容:
file_path = tk.filedialog.askopenfilename()
mongo_client = MongoClient()
db = mongo_client.football
file_path2 = file_path + ".json"
df = pd.read_csv(file_path) # loading csv file
df.to_json(file_path2) # saving to json file
with open(file_path2) as f:
file_data = json.load(f)
db.joueurs.insert_many([file_data])
我想将它们插入到不同的文档中。
这是一种读取 CSV 并将数据加载到 MongoDB 集合中的方法。假设文件中的数据如下:
col1,col2
a,1
b,2
以下 Python 和 PyMongo 代码将在集合中创建两个文档。
data = []
file_name = "some.csv"
with open(file_name, newline='') as csvfile:
reader = csv.DictReader(csvfile) # using Python's csv module
for row in reader:
data.append(row)
result = collection.insert_many(data)
集合中生成的文档:
{ "_id" : ObjectId("626fc502c9bbf326c869f434"), "col1" : "a", " col2" : "1" }
{ "_id" : ObjectId("626fc502c9bbf326c869f435"), "col1" : "b", " col2" : "2" }