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

2022-01-31 00:00:00 arrays mongodb sorting javascript

我有一组学生,每个学生的记录如下所示,我想按 score 的降序对 scores 数组进行排序.

I have a collection of students, each with a record that looks like the following and I want to sort the scores array in descending order of score.

这个咒语在 mongo shell 上是什么样子的?

what does that incantation look like on the mongo shell?

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

我正在尝试这个咒语......

I'm trying this incantation....

 doc = db.students.find()

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

但它不起作用.

推荐答案

您将需要在应用程序代码中操作嵌入数组或使用新的 聚合框架.

You will need to manipulate the embedded array in your application code or using the new Aggregation Framework in MongoDB 2.2.

mongo shell 中的示例聚合:

Example aggregation in the mongo shell:

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
}

相关文章