Task is to find,sort,and remove the student with 'type': "homework" and with the lowest score using MongoDB. I also tried to use toArray()
function,but it gave an error. Now I try to move on in document as a number of counter and to remove the last sorted document with the lowest score.
import pymongo
import sys
#establish a connection to the database
connection = pymongo.MongoClient("mongodb://localhost")
def delete_lowest_doc():
#get a handle to the students database
db=connection.students
grades = db.grades
try:
for i in range(0,grades.find().count()):
docs_1 = grades.find({'type':"homework", 'student_id':i}).sort(['score',-1])
counter_1 = grades.find({'type':"homework",'student_id':i})
counter_2 = counter_1.sort(['score',-1]).count()
while (counter_2>0):
doc = docs_1.next();
counter_2=counter_2-1;
grades.remove(doc)
except Exception as e:
print ("Unexpected error:", type(e), e)
delete_lowest_doc()
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…