Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in SQL by (5k points)

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

This is the database in Json format where I want to delete the field with the low score. After deleting, my database should look like:

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

1 Answer

0 votes
by (10.2k points)

Here, you can use findAndModify:

db.students.findAndModify({

     query: {"student_id" : 1, "type" : "homework"},

     sort: {"score": 1},

     remove: true

})
 

 findOneAndDelete command can also be used in MongoDB version 3.2:

db.students.findOneAndDelete(

     {"student_id" : 1, "type" : "homework"},

     {sort: {"score": 1}}

)

These queries will do the following things:

  • They will filter out documents based on the student_id and type

  • Sort documents ascendingly based on the score and then act on the first value after sort, which is the one with the minimum score.

  • Delete the document with a minimum homework score. 

 

 you can also use the find_one_and_delete method of mongoDB  to achieve the same in 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)

This method can resolve the query. 

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...