rebuild file struct
This commit is contained in:
56
mongo_manager.py
Normal file
56
mongo_manager.py
Normal file
@@ -0,0 +1,56 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
from pymongo import MongoClient
|
||||
|
||||
# 连接到 MongoDB
|
||||
client = MongoClient('mongodb://root:lostecho@192.168.31.3:27017/')
|
||||
# 选择数据库
|
||||
db = client['songyi']
|
||||
# 选择集合
|
||||
collection = db['course_content']
|
||||
|
||||
|
||||
def insert_course_content(file_path):
|
||||
file_name = os.path.basename(file_path)
|
||||
course_id = file_name
|
||||
print(course_id)
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8-sig') as file:
|
||||
data = json.load(file)
|
||||
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}")
|
||||
|
||||
def get_course_content(id_to_query):
|
||||
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("加载后的数据:" + loaded_data)
|
||||
return json_str
|
||||
else:
|
||||
print(f"未找到 _id 为 {id_to_query} 的文档。")
|
||||
except Exception as e:
|
||||
print(f"错误:查询或处理数据时出现未知错误:{e}")
|
||||
Reference in New Issue
Block a user