8

MongoDB新手在这里...

我有一个集合如下...

    > db.students.find({_id:22},{scores:[{type:'exam'}]}).pretty()
    {
        "_id" : 22,
        "scores" : [
            {
                "type" : "exam",
                "score" : 75.04996547553947
            },
            {
                "type" : "quiz",
                "score" : 10.23046475899236
            },
            {
                "type" : "homework",
                "score" : 96.72520512117761
            },
            {
                "type" : "homework",
                "score" : 6.488940333376703
            }
        ]
    }

如何通过 mongo shell 仅显示测验分数?

4

1 回答 1

24

您的原始示例中有一些语法可能没有达到您的预期......也就是说,您的意图似乎是只匹配特定类型的分数(示例中的“考试”,您的描述中的“测验” )。

下面是一些使用 MongoDB 2.2 shell 的示例。

$elemMatch投影

您可以使用$elemMatch 投影返回数组中的第一个匹配元素:

db.students.find(
    // Search criteria
    { '_id': 22 },

    // Projection
    { _id: 0, scores: { $elemMatch: { type: 'exam' } }}
)

结果将是每个文档的数组的匹配元素,例如:

{ "scores" : [ { "type" : "exam", "score" : 75.04996547553947 } ] }

聚合框架

如果要显示多个匹配值或重塑结果文档而不是返回完整匹配的数组元素,可以使用聚合框架

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

    // Convert embedded array into stream of documents
    { $unwind: '$scores' },

    // Only match scores of interest from the subarray
    { $match: {
        'scores.type' : 'exam'
    }},

    // Note: Could add a `$group` by _id here if multiple matches are expected

    // Final projection: exclude fields with 0, include fields with 1
    { $project: {
        _id: 0,
        score: "$scores.score"
    }}
)

在这种情况下,结果包括:

{ "result" : [ { "score" : 75.04996547553947 } ], "ok" : 1 }
于 2012-11-19T12:12:48.677 回答