将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模块。