2014년 12월 9일 화요일

What is the correct sytax of PyMongo to iterate in cursor ?

I wrote something like this :
db = connection.students
grades = db.grades
cursor = db.grades.find({"type":"homework"}).sort({student:1,score:1}) 
I need to iterate through cursor and remove the document i find for each student by noticing a change in student id.
I need to delete the lowest score for each student

Please help me how to write it correnct



The general pattern for looping over an iterable (like the cursor returned by .find()) in Python is

for val in iterable:
    # do stuff with val

To print all of the result documents from the find query:

for doc in db.grades.find({"type":"homework"}).sort({student:1,score:1}):
    print(doc)

Hopefully, that will be enough to get you started writing the correct logic around the cursor iteration to remove each student's lowest score.



Careful that you don't delete the only score a particular student has  :)



The code you wrote missing something, i need to find out somehow, how to find out when the Student Id is changed and remove only this



I thought about this

db = connection.students
grades = db.grades

VarStudentId = 0 
cursor = db.grades.find({"type":"homework"}).sort({student:1,score:1}) 

for doc in cursor
if StudentID = doc.student_id
grades.remove({student_id : doc.student_id})
else
VarStudentId = doc.student_id



If you remove this lowest grade, what happens to the next record of
this student?

If a student only has a single grade, then what?

You should work out the solution logically first.  Once you know
exactly how to do it, then worry about how to write code for it.


댓글 없음:

댓글 쓰기