如何排序在MongoDB中收集记录中数组 [英] how to sort array inside collection record in mongoDB

查看:102
本文介绍了如何排序在MongoDB中收集记录中数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MongoDB的小白在这里...

MongoDB noob here...

好吧,我有个同学的集合,每个看起来像下面的....我要排序的类型的记载:'功课'按降序排列得分

Ok, I have a collection of students, each with a record that looks like the following.... I want to sort the 'type' : 'homework' scores in descending order.

这是什么咒语看起来像蒙戈的壳呢?

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

但它不工作。

推荐答案

您将需要处理应用程序中的code中的嵌入式阵列,或使用新的 MongoDB中2.2聚合框架

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

蒙戈 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
}

这篇关于如何排序在MongoDB中收集记录中数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆