MongoDB游标实例索引错误:‘no such item for cursor instance’求助
问题分析与解决
报错原因
- MongoDB的
find()方法返回的是游标(Cursor),而非列表,游标不支持随机索引访问([index]),且属于一次性迭代对象,一旦遍历耗尽后再次访问就会抛出索引错误。 - 你代码里的
get_department_courses是未转换的游标,循环中直接用get_department_courses[index]访问元素是错误用法。 - 无法保证查询返回的课程数与讲师数完全匹配,当课程数量少于讲师数量时,也会触发索引越界问题。
修复后的代码
from bson.objectid import ObjectId def update_instructor_course(college, department, department_course_list): # 将游标转为列表,支持随机访问且避免游标耗尽问题 get_department_courses = list(courses.find({"college": college, "department": department})) get_department_instructors = list(employees.find({"college": college, "department": department}))[:len(department_course_list)] # 自动配对讲师与课程,避免手动索引导致的越界 matched_pairs = zip(get_department_instructors, get_department_courses) for instructor, course in matched_pairs: # 更新讲师的课程信息 employees.update_one( {"_id": ObjectId(instructor["_id"])}, {"$set": {"course": [course['course_code']]}} ) # 更新课程的讲师信息 courses.update_one( {"_id": ObjectId(course["_id"])}, {"$set": {"instructor": instructor['employee_id']}} )
关键优化点
- 游标转列表:用
list()将find()返回的游标转为列表,确保可以安全进行多次访问和索引操作。 - 用
zip()配对:自动匹配讲师与课程,当其中一方数量不足时会自动停止循环,避免索引越界。 - 可选校验:如果需要严格匹配
department_course_list的长度,可在转列表后添加校验逻辑:if len(get_department_courses) < len(get_department_instructors): # 处理课程数量不足的情况,比如截断讲师列表 get_department_instructors = get_department_instructors[:len(get_department_courses)]
内容的提问来源于stack exchange,提问作者Spencer Brian
相关产品推荐
相关产品推荐

