如何在 mongodb 3.2 中删除一个同名字段


{ "_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 }

使用 findAndModify

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}}
)

这些查询将:

  1. 根据student_idtype筛选所有文档
  2. 根据score升序对文档进行排序,然后对排序后的第一个值,即得分最低的值
  3. 删除家庭作业分数最低的文档

我不是 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)

最新更新