【问题标题】:How can I delete one field with same name in mongodb 3.2?如何在 mongodb 3.2 中删除一个同名字段?
【发布时间】:2016-06-06 18:56:38
【问题描述】:
{ "_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 }

【问题讨论】:

    标签: python json mongodb


    【解决方案1】:

    使用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 专家,但是你可以在 python 中使用find_one_and_delete 方法来实现:

    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)
    

    【讨论】:

    • 非常感谢你 :) :) !!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多