Search code examples
pythonmongodbpymongo

no such item for cursor instance


This is the code I used to retrieve data from two different collections and matched them on the department criteria. However after running the function for 7 times, I get an index Error of "no such item for cursor instance"

def update_instructor_course(college,department,department_course_list):
    get_department_courses = (courses.find({"college": college, "department": department}))
    get_department_instructors = (employees.find({"college":college, "department": department}))[:len(department_course_list)]

    for index, instructor in enumerate(get_department_instructors):
        employees.update_one({"_id": ObjectId(instructor["_id"])},{"$set": {"course": [get_department_courses[index]['course_code']]}})
        courses.update_one({"_id":ObjectId(get_department_courses[index]["_id"])}, {"$set":{"instructor":instructor['employee_id']}})```

Solution

  • The find method always returns an instance of the cursor, in order to work with it as a list, you need to use the to_list(...) method, which accepts the number of elements to form the list or None.

    get_department_courses = courses.find({"college": college, "department": department}).to_list(None)