比较数组元素,删除得分最低的元素

时间:2015-04-03 21:07:59

标签: mongodb database nosql

学校数据库中有200个文件。我必须删除每个包含"类型":"" homework"和最低分。

    {
        "_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
    }
必须删除

,因为得分= 6.6< 35.8

我对所有文件进行了分类:

db.students.find({"scores.type":"homework"}).sort({"scores.score":1})

但我不知道如何删除分数最低的文档并输入:homework ???  注意:如何通过不使用聚合方法来解决它?例如,通过排序然后更新。

2 个答案:

答案 0 :(得分:1)

这可以通过几个步骤完成。第一步是使用汇总框架和$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" } } } ] )

第二步是遍历上面的字典并在更新查询中使用$pull运算符从数组中删除元素,如下所示:

for result in lowest_scores_docs["result"]:
    db.school.update({ "_id": result["_id"] }, 
        { "$pull": { "scores": { "score": result["lowest_score"] } } } )

答案 1 :(得分:0)

import pymongo
import sys

# connnecto to the db on standard port
connection = pymongo.MongoClient("mongodb://localhost")

db = connection.school           # attach to db
students = db.students        # specify the colllection


try:

        cursor = students.find({})
        print(type(cursor))
        for doc in cursor:
            hw_scores = []
            for item in doc["scores"]:
                if item["type"] == "homework":
                    hw_scores.append(item["score"])
            hw_scores.sort()
            hw_min = hw_scores[0]
            #students.update({"_id": doc["_id"]},
             #           {"$pull":{"scores":{"score":hw_min}}})


except:
    print ("Error trying to read collection:" + sys.exc_info()[0])