【问题标题】:Sort JSON document by values embedded in an array of objects按对象数组中嵌入的值对 JSON 文档进行排序
【发布时间】:2019-12-03 09:19:38
【问题描述】:

我有一份格式如下的文件。目标是按学生姓名对文档进行分组,并按升序对文档进行排序。完成后,遍历排名(在学生内),如果每个后续排名都大于前一个,则需要增加版本字段。作为管道的一部分,student_name 将传递给我,因此按学生姓名匹配应该是好的,而不是分组。

注意:使用 python 进行了尝试,并在一定程度上起作用。 python 解决方案也很棒!

    {
        "_id" : ObjectId("5d389c7907bf860f5cd11220"),
        "class" : "I",
        "students" : [
            {
                "student_name" : "AAA",
                "Version" : 2,
                "scores" : [
                    {
                        "value" : "50",
                        "rank" : 2
                    },
                    {
                        "value" : "70",
                        "rank" : 1
                    }
                ]
            },
            {
                "student_name" : "BBB",
                "Version" : 5,
                "scores" : [
                    {
                        "value" : 80,
                        "rank" : 2
                    },
                    {
                        "value" : 100,
                        "rank" : 1
                    },
                    {
                        "value" : 100,
                        "rank" : 1
                    }
                ]
            }
        ]
    }

我试过这段代码来排序

    def version(student_name):
        db.column.aggregate(
            [
           {"$unwind": "$students"},
           {"$unwind": "$students.scores"},
           {"$sort" : {"students.scores.rank" : 1}},
           {"$group" : {"students.student_name}
            ]
       )

for i in range(0,(len(students.scores)-1)):
    if students.scores[i].rank < students.scores[i+1].rank:
       tag.update_many(
           {"$inc" : {"students.Version":1}}
       )

学生 AAA 的预期输出应该是

    {
        "_id" : ObjectId("5d389c7907bf860f5cd11220"),
        "class" : "I",
        "students" : [
            {
                "student_name" : "AAA",
                "Version" : 3, #version incremented
                "scores" : [
                    {
                        "value" : "70",
                        "rank" : 1
                    },
                    {
                        "value" : "50",
                        "rank" : 2
                    }
                ]
            }

【问题讨论】:

  • 你能添加一个你预期输出的示例文档吗
  • 我已经添加了预期的输出并解释了版本是如何递增的

标签: python-3.x mongodb aggregation-framework pymongo


【解决方案1】:

我能够对文档进行排序。

 pipeline = [
            {"$unwind": "$properties"},
            {"$unwind": "$properties.values"},
            {"$sort" : {"$properties.values.rank" : -1}},
            {"$group": {"_id" : "$properties.property_name", "values" : {"$push" : "$properties.values"}}}
        ]

import pprint
pprint.pprint(list(db.column.aggregate(pipeline)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 2012-11-25
    • 1970-01-01
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多