12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- # 导入必要的库
- from pymongo import MongoClient
- import pandas as pd
- def export_to_excel(db_name, collection_name, fields, output_file):
- """
- 从MongoDB导出特定字段到Excel文件。
- 参数:
- - db_name: 数据库名称
- - collection_name: 集合名称
- - fields: 要导出的字段列表(例如 ['name', 'age'])
- - output_file: 输出的Excel文件名
- """
- # 连接到MongoDB
- client = MongoClient('mongodb://192.168.3.149:27180/')
- db = client[db_name]
- collection = db[collection_name]
- # 构建查询和投影
- projection = {field: 1 for field in fields}
- # 查询数据
- data = collection.find({"flag":3},projection)
- # 将数据转换为DataFrame
- df = pd.DataFrame(list(data))
- # 导出到Excel文件
- df.to_excel(output_file, index=False)
- if __name__ == "__main__":
- # 连接到 MongoDB
- db_name = 'data_quality' # 替换为你的数据库名称
- # collection_name = 'standard_sample_data_all' # 替换为你的集合名称
- collection_name = 'bidding_20241128_ai' # 替换为你的集合名称
- # 定义参数
- fields = ['_id', 'site','toptype','subtype','area','city','buyer','projectname','projectcode','budget','s_winner','bidamount','multipackage','href','jyhref'] # 替换为你需要导出的字段
- output_file = 'output.xlsx'
- # 调用函数导出数据
- export_to_excel(db_name, collection_name, fields, output_file)
- print(f"数据已成功导出到 {output_file}")
|