答:
from pymongo import MongoClient
# 连接到MongoDB数据库
client = MongoClient('mongodb://localhost:27017/')
db = client.your_database_name # 替换为你的数据库名称
collection = db.your_collection_name # 替换为你的集合名称
# 查询所有学生信息
students = collection.find()
# 初始化一个字典来存储分组后的学生信息
grouped_students = {
'不及格': [],
'良好': [],
'优秀': [],
'天才': []
}
# 遍历学生信息进行分组
for student in students:
score = student['成绩'] # 假设学生的成绩字段是'成绩'
name = student['姓名'] # 假设学生的姓名字段是'姓名'
category = ''
if score < 60:
category = '不及格'
elif score < 75:
category = '良好'
elif score < 90:
category = '优秀'
else:
category = '天才'
grouped_students[category].append({'姓名': name, '成绩': score})
# 打印每个分组的所有学生的姓名和成绩
for category, students_list in grouped_students.items():
print(f'{category}:')
for student in students_list:
print(f'姓名:{student["姓名"]}, 成绩:{student["成绩"]}')
print() # 打印空行以分隔不同的成绩分组