extract subarray value in mongodb

时间秒杀一切 提交于 2019-12-02 18:36:49

You have some syntax in your original example which probably isn't doing what you expect .. that is, it looks like your intent was to only match scores for a specific type ('exam' in your example, 'quiz' by your description).

Below are some examples using the MongoDB 2.2 shell.

$elemMatch projection

You can use the $elemMatch projection to return the first matching element in an array:

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

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

The result will be the matching element of the array for each document, eg:

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

Aggregation Framework

If you want to display more than one matching value or reshape the result document instead of returning the full matching array element, you can use the Aggregation Framework:

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"
    }}
)

The result in this case includes would be:

{ "result" : [ { "score" : 75.04996547553947 } ], "ok" : 1 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!