Files
songyi/mongo_manager.py
2025-04-16 09:38:48 +08:00

59 lines
1.7 KiB
Python

import os
from pymongo import MongoClient
import json
# 连接到 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}")