I try to import a CSV file in mongodb, but with my code, it inserts all in only one document:
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])
I want to insert them in differents documents.
CodePudding user response:
Here is a way to read a CSV and load the data into a MongoDB collection. Assuming the data in the file is as follows:
col1,col2
a,1
b,2
The following Python and PyMongo code will create two documents in the collection.
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)
The resulting documents in the collection:
{ "_id" : ObjectId("626fc502c9bbf326c869f434"), "col1" : "a", " col2" : "1" }
{ "_id" : ObjectId("626fc502c9bbf326c869f435"), "col1" : "b", " col2" : "2" }