rebuild file struct
This commit is contained in:
70
json/insert_mongodb.py
Normal file
70
json/insert_mongodb.py
Normal file
@@ -0,0 +1,70 @@
|
||||
import json
|
||||
from pymongo import MongoClient
|
||||
|
||||
import os
|
||||
|
||||
# 指定目录路径
|
||||
directory = './'
|
||||
|
||||
# 连接到 MongoDB
|
||||
client = MongoClient('mongodb://root:lostecho@192.168.31.3:27017/')
|
||||
# 选择数据库
|
||||
db = client['songyi']
|
||||
# 选择集合
|
||||
collection = db['course_content']
|
||||
|
||||
# 遍历目录下的所有文件
|
||||
for filename in os.listdir(directory):
|
||||
if filename.endswith('.json'):
|
||||
file_path = os.path.join(directory, filename)
|
||||
course_id = filename.split('.')[0]
|
||||
print(course_id)
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8-sig') as file:
|
||||
# content = file.read()
|
||||
# print(f"文件 {filename} 的内容如下:")
|
||||
# print(content)
|
||||
data = json.load(file)
|
||||
# 为每个文档添加指定的 _id
|
||||
# print(data["data"][0]["course_id"])
|
||||
if isinstance(data, list):
|
||||
for i, document in enumerate(data):
|
||||
document["_id"] = course_id
|
||||
else:
|
||||
data["_id"] = course_id
|
||||
if isinstance(data, list):
|
||||
collection.insert_many(data)
|
||||
else:
|
||||
collection.insert_one(data)
|
||||
except FileNotFoundError:
|
||||
print(f"错误:文件 {file_path} 未找到。")
|
||||
except Exception as e:
|
||||
print(f"错误:处理文件 {file_path} 时出现未知错误:{e}")
|
||||
|
||||
|
||||
id_to_query = str(1)
|
||||
|
||||
try:
|
||||
|
||||
# 根据 _id 查询单个文档
|
||||
document = collection.find_one({"_id": id_to_query})
|
||||
|
||||
if document:
|
||||
# 移除 _id 字段中的 ObjectId 对象,因为它不能直接被 JSON 序列化
|
||||
document.pop("_id", None)
|
||||
|
||||
# 将查询结果转换为 JSON 字符串
|
||||
json_str = json.dumps(document)
|
||||
|
||||
# 使用 json.loads 加载 JSON 字符串
|
||||
loaded_data = json.loads(json_str)
|
||||
|
||||
print("加载后的数据:")
|
||||
print(loaded_data)
|
||||
else:
|
||||
print(f"未找到 _id 为 {id_to_query} 的文档。")
|
||||
except Exception as e:
|
||||
print(f"错误:查询或处理数据时出现未知错误:{e}")
|
||||
|
||||
# 关闭连接
|
||||
client.close()
|
||||
Reference in New Issue
Block a user