本文介绍了比较数组元素,删除具有最低分数的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 学校db有200份文件。我必须删除每个文档有类型:家庭作业和最低的分数。 {_id:0,name:aimee Zank,scores: [ {type:exam,score:1.463179736705023 }, {type:quiz,score:11.78273309957772 }, {type:homework,score 6.676176060654615 }, {type:homework,score:35.8740349954354 } ] } 例如, {type:homework,score:6.676176060654615 } 必须删除,因为score = 6.6< 35.8 我对所有文档进行了排序: db。 students.find({scores.type:homework})。sort({scores.score:1}) 但我不知道如何删除具有最低分数和类型的文档:homework? 注意:如何通过不使用聚合方法来解决它?例如,通过排序然后更新。解决方案这可以通过几个步骤完成。第一步是使用具有最小分数的文档列表,使用 $ match , $ unwind 和 $ group 运算符简化您的文档,以找到每个文档的最低分数: lowest_scores_docs = db .school.aggregate([ {$ match:{scores.type:homework}}, {$ unwind:$ scores},{$ match :{scores.type:homework}}, {$ group:{_id:$ _ id,lowest_score:{$ min:$ scores.score }第二步是循环遍历上面的字典,并使用 $ b $ pull 运算符在更新查询中从数组中删除元素,如下所示: 结果为lowest_scores_docs [ $$$:{scores:{score:result [result]:: lowest_score]}}}) There are 200 documents in school db. I must remove each document which has "type":"homework" and the lowest score. { "_id" : 0, "name" : "aimee Zank", "scores" : [ { "type" : "exam", "score" : 1.463179736705023 }, { "type" : "quiz", "score" : 11.78273309957772 }, { "type" : "homework", "score" : 6.676176060654615 }, { "type" : "homework", "score" : 35.8740349954354 } ] }For example,here { "type" : "homework", "score" : 6.676176060654615 }must be removed as score = 6.6 < 35.8I sorted all the documents like this:db.students.find({"scores.type":"homework"}).sort({"scores.score":1})But I do not know how then to remove the doc having the lowest score and type:homework??? NOTE: how to solve it by not using aggregation method? E.g., by sorting and then updating. 解决方案 This can be done in a couple of steps. The first step is to grab a list of the documents with the minimum score by using the aggregation framework with $match, $unwind and $group operators that streamlines your documents to find the minimum score for each document:lowest_scores_docs = db.school.aggregate([ { "$match": {"scores.type": "homework"} }, { "$unwind": "$scores" }, { "$match": {"scores.type": "homework"} }, { "$group": { "_id":"$_id", "lowest_score": {"$min": "$scores.score" } } } ] )The second step is to loop through the dictionary above and use the $pull operator in the update query to remove the element from the array as follows:for result in lowest_scores_docs["result"]: db.school.update({ "_id": result["_id"] }, { "$pull": { "scores": { "score": result["lowest_score"] } } } ) 这篇关于比较数组元素,删除具有最低分数的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-29 23:49