小编典典

如何在mongoDB中的集合记录中对数组进行排序

javascript

MongoDB菜鸟在这里…

好的,我有一个学生集合,每个学生的记录看起来都如下所示:我想按降序对“类型”:“作业”分数进行排序。

mongo外壳上的咒语是什么样的?

> db.students.find({'_id': 1}).pretty()
{
        "_id" : 1,
        "name" : "Aurelia Menendez",
        "scores" : [
                {
                        "type" : "exam",
                        "score" : 60.06045071030959
                },
                {
                        "type" : "quiz",
                        "score" : 52.79790691903873
                },
                {
                        "type" : "homework",
                        "score" : 71.76133439165544
                },
                {
                        "type" : "homework",
                        "score" : 34.85718117893772
                }
        ]
}

我正在尝试这个咒语…

 doc = db.students.find()

 for (_id,score) in doc.scores:
     print _id,score

但它不起作用。


阅读 929

收藏
2020-04-25

共1个答案

小编典典

您将需要在应用程序代码中或在MongoDB 2.2中使用新的AggregationFramework来操纵嵌入式数组。

mongoShell中的示例聚合:

db.students.aggregate(
    // Initial document match (uses index, if a suitable one is available)
    { $match: {
        _id : 1
    }},

    // Expand the scores array into a stream of documents
    { $unwind: '$scores' },

    // Filter to 'homework' scores 
    { $match: {
        'scores.type': 'homework'
    }},

    // Sort in descending order
    { $sort: {
        'scores.score': -1
    }}
)

样本输出:

{
    "result" : [
        {
            "_id" : 1,
            "name" : "Aurelia Menendez",
            "scores" : {
                "type" : "homework",
                "score" : 71.76133439165544
            }
        },
        {
            "_id" : 1,
            "name" : "Aurelia Menendez",
            "scores" : {
                "type" : "homework",
                "score" : 34.85718117893772
            }
        }
    ],
    "ok" : 1
}
2020-04-25