在mongodb中提取子数组值

the*_*nso 7 mongodb mongo-shell

MongoDB noob在这里......

我有一个如下集合......

    > 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
            }
        ]
    }
Run Code Online (Sandbox Code Playgroud)

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

Ste*_*nie 22

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

以下是使用MongoDB 2.2 shell的一些示例.

$elemMatch 投影

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

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

    // Projection
    { _id: 0, scores: { $elemMatch: { type: 'exam' } }}
)
Run Code Online (Sandbox Code Playgroud)

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

{ "scores" : [ { "type" : "exam", "score" : 75.04996547553947 } ] }
Run Code Online (Sandbox Code Playgroud)

聚合框架

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

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"
    }}
)
Run Code Online (Sandbox Code Playgroud)

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

{ "result" : [ { "score" : 75.04996547553947 } ], "ok" : 1 }
Run Code Online (Sandbox Code Playgroud)

  • Stennie说,他建造了数据库. (5认同)