3

我正在学习使用 python 语言的 mongo 课程。我必须删除/删除每个学生的最低作业成绩。通过这个查询,我提取了作业成绩,并按学生和成绩对它们进行了排序

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

5 回答 5

4

这是用 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; 
    }
});
于 2012-11-03T23:45:25.987 回答
1

哈哈,这是我做功课的方法:

import pymongo
import sys
connection = pymongo.Connection("mongodb://localhost", safe=True)
db=connection.students
grades = db.grades

def delete_lowest_score():

print "grading nice?! look at these scores now!"

query = {'type':'homework'}
sort = [('student_id',pymongo.ASCENDING),('score',pymongo.ASCENDING)]
track = -1

try:

    cursor = grades.find(query).sort(sort)

except:
    print "Unexpected error:", sys.exc_info()[0]

for doc in cursor:
    if doc['student_id'] != track:
        grades.remove(doc)
        track = doc['student_id']


delete_lowest_score()
于 2012-11-04T19:56:06.843 回答
1
connection = pymongo.MongoClient("mongodb://localhost" , safe = True)
db = connection.students           
collection = db.grades      
query = {}
iter = collection.find({'type':'homework'}).sort([('student_id',pymongo.ASCENDING),  ('score',pymongo.ASCENDING)])
try:
    for doc in iter:
    nextStudentId =  iter.next()
        if ((doc['student_id']) == nextStudentId['student_id']):
            collection.remove({"_id":doc['_id']})
except:
    print "Error trying to read collection:" + sys.exc_info()[0]
于 2013-12-09T17:03:47.497 回答
0

我一直在上同样的课程。

现在截止日期已经过去......以下似乎可以解决问题:

import pymongo, sys
connection = pymongo.Connection("mongodb://localhost",safe=True)
db=connection.students
### s1 for sample (a cursor (iterable)); sort first by "student_id"
s1=db.grades.find({"type":"homework"}).sort([("student_id", pymongo.ASCENDING),("score", pymongo.DESCENDING)])
### c1 is a counter; note every 2nd record will be the lower score for that student 
c1=1
for d in s1: # d for document
    id1=d["_id"] # id1 is particular id
    if c1%2==0: # c1 divisible by 2?
       db.grades.remove({"_id":id1})
    c1=c1+1

这将修改原始集合,删除作业中两个分数中较低的所有记录,留下 600 条记录。更改为mongo界面,您将能够复制Java 此处给出的所有示例。

我承认这是@scicholas 答案的一个变体,只是有点简洁。起初我在使用游标时遇到了麻烦,因为在运行上述内容之前迭代记录。如果您在 Python 中以交互方式检查它,请不要忘记s1.rewind()先重置它。

于 2012-11-11T03:33:49.360 回答
0

这是在 C# 中

static async Task MainAsync(string[] args)
    {
        var connectionString = "mongodb://localhost:27017";
        var client = new MongoClient(connectionString);

        var db = client.GetDatabase("students");
        var col = db.GetCollection<Grade>("grades");

        var builder = Builders<Grade>.Filter;
        var filter = builder.Eq("type", "homework");
        var gradedHomework = await col.Find(filter)
                .Sort(Builders<Grade>.Sort.Ascending("student_id").Ascending("score"))
                .ToListAsync();

        var sid = -1;

        foreach (Grade doc in gradedHomework)
        {

            if (sid != doc.student_id)
            {
               var result = await col.DeleteOneAsync(x => x.Id == doc.Id);
                Console.WriteLine(doc.score);
                sid = doc.student_id;
            }

        }



    }



    public class Grade
    {
        public object Id { get; set; }
        public int student_id { get; set; }
        public string type { get; set; }
        public double score { get; set; }
    }
}
于 2016-08-16T05:41:44.343 回答