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

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

但它不起作用.

推荐答案

您需要在应用程序代码中操作嵌入式数组,或者使用MongoDB 2.2中的新Aggregation Framework.

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相关问答推荐

会话的Mongo-go驱动程序版本.Copy()

如何对嵌套在另一个数组中的数组中的字段执行查找?

我无法将文档发送到我的MongoDB集合,因为它告诉我使文档无效

如何在MongoDB中通过限制和跳过查找项进行匹配

数组中字符串的Mongo查询集合和推送到新数组嵌套对象

MongoDB即使在使用索引时也很慢

MongoDB:嵌套数组计数+原始文档

如何将以下聚合查询转换为 bson 并在 golang 中执行

如何使用 Golang 库获取 MongoDB 版本?

在亚马逊 EC2 上托管 nodeJS/mongoose Web 应用程序

MongoDB中的readPreference和readConcern有什么区别?

Mongoexport 在日期范围内使用 $gt 和 $lt 约束

从 MongoDB find() 结果集中识别最后一个文档

Flask and Mongo

如何在任意深度查找 MongoDB 字段名称

MongoDB 中的所有列

mongodb nodejs - 转换圆形 struct

Flask:设置应用程序和请求特定的属性?

如何使用 mgo 从 golang 中的 mongodb 集合中 Select 所有记录

mongoose中的 Date.now() 和 Date.now 有什么区别?