{ "_id" : { "$oid" : "50906d7fa3c412bb040eb57b" }, "student_id" : 1, "type" : "exam", "score" : 74.20010837299897 }
{ "_id" : { "$oid" : "50906d7fa3c412bb040eb57c" }, "student_id" : 1, "type" : "quiz", "score" : 96.76851542258362 }
{ "_id" : { "$oid" : "50906d7fa3c412bb040eb57d" }, "student_id" : 1, "type" : "homework", "score" : 21.33260810416115 }
{ "_id" : { "$oid" : "50906d7fa3c412bb040eb57e" }, "student_id" : 1, "type" : "homework", "score" : 44.31667452616328 }
上面给出的是json格式的数据库。我想删除低分的字段(作业)。 db.grades(######) 请写下解决方案代替###### 删除后,我的数据库应该看起来像下面给出的数据
{ "_id" : { "$oid" : "50906d7fa3c412bb040eb57b" }, "student_id" : 1, "type" : "exam", "score" : 74.20010837299897 }
{ "_id" : { "$oid" : "50906d7fa3c412bb040eb57c" }, "student_id" : 1, "type" : "quiz", "score" : 96.76851542258362 }
{ "_id" : { "$oid" : "50906d7fa3c412bb040eb57e" }, "student_id" : 1, "type" : "homework", "score" : 44.31667452616328 }
答案 0 :(得分:3)
db.students.findAndModify({
query: {"student_id" : 1, "type" : "homework"},
sort: {"score": 1},
remove: true
})
在MongoDB 3.2中,您还可以使用findOneAndDelete
:
db.students.findOneAndDelete(
{"student_id" : 1, "type" : "homework"},
{sort: {"score": 1}}
)
这些查询将:
student_id
和type
score
递增对文档进行排序,然后对其执行操作
排序后的第一个值,即得分最低的值我不是PyMongo的专家,但您可以使用find_one_and_delete
方法在python中实现相同的目标:
filter_by_student_and_type = {'student_id' : 1, 'type' : 'homework'}
sort_by_score = [('score', pymongo.ASCENDING )]
db.students.find_one_and_delete(filter_by_student_and_type, sort=sort_by_score)