將MongoDB數據保存為CSV文件可以通過以下步驟實現:
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['your_database_name']
collection = db['your_collection_name']
data = collection.find()
data_list = list(data)
import csv
csv_file = 'data.csv'
csv_columns = data_list[0].keys()
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
for data in data_list:
writer.writerow(data)
以上代碼將MongoDB中的數據保存到名為data.csv的CSV文件中。請確保您已安裝pymongo和csv模塊。