gpt4 book ai didi

mongodb - 如何迭代并排序

转载 作者:可可西里 更新时间:2023-11-01 09:25:03 26 4
gpt4 key购买 nike

我正在学习使用 Python 语言的 mongo 类(class)。我必须删除/删除每个学生的最低作业成绩。通过这个查询,我调出了作业成绩,并按学生和年级对它们进行了排序

db.grades.find( { 'type' : 'homework' }, { 'student_id' : 1, 'score' : 1, '_id' : 0}).sort({ 'student_id' : 1, 'score' : 1 })

我安排了查询,以便仅显示学生 ID 和分数,如下所示。这些只是前 10 名学生。实际上有 400 个。现在我必须对它们进行排序并删除每个的最低分数。

问题是,我如何对此进行排序以删除每个学生的最低成绩?

{ "student_id" : 0, "score" : 14.8504576811645 }
{ "student_id" : 0, "score" : 63.98402553675503 }
{ "student_id" : 1, "score" : 21.33260810416115 }
{ "student_id" : 1, "score" : 44.31667452616328 }
{ "student_id" : 2, "score" : 60.9750047106029 }
{ "student_id" : 2, "score" : 97.75889721343528 }
{ "student_id" : 3, "score" : 50.81577033538815 }
{ "student_id" : 3, "score" : 92.71871597581605 }
{ "student_id" : 4, "score" : 5.244452510818443 }
{ "student_id" : 4, "score" : 28.656451042441 }
{ "student_id" : 5, "score" : 23.29430953857654 }
{ "student_id" : 5, "score" : 41.21853026961924 }
{ "student_id" : 6, "score" : 81.23822046161325 }
{ "student_id" : 6, "score" : 89.72700715074382 }
{ "student_id" : 7, "score" : 63.35102050393443 }
{ "student_id" : 7, "score" : 85.56691619291915 }
{ "student_id" : 8, "score" : 66.42784200049636 }
{ "student_id" : 8, "score" : 67.29005808579812 }
{ "student_id" : 9, "score" : 16.60130789148128 }
{ "student_id" : 9, "score" : 75.29561445722392 }

最佳答案

这是一个用 JavaScript 编写的解决方案

var students = db.grades.find( { 'type' : 'homework' }, { 'student_id' : 1, 'score' : 1, '_id' : 0}).sort({ 'student_id' : 1, 'score' : 1 })

// Create a variable to track student_id so we can detect when it changes
var id = "";

// Loop through our query results. Each document in the query is passed into a function as 'student'
students.forEach(function (student) {
if (id !== student.student_id) {
db.grades.remove(student)
id = student.student_id;
}
});

关于mongodb - 如何迭代并排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13189260/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com