在mongodb中提取子数组值 [英] extract subarray value in mongodb

查看:68
本文介绍了在mongodb中提取子数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MongoDB菜鸟在这里...

MongoDB noob here...

我有如下收藏...

    > 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显示测验分数?

how do I display only the quiz score via mongo shell?

推荐答案

您在原始示例中有一些语法可能未达到您的期望.特定类型(在您的示例中为考试",在说明中为测验").

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).

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

Below are some examples using the MongoDB 2.2 shell.

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

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 } ] }

聚合框架

如果要显示多个匹配值或调整结果文档的形状,而不是返回完整的匹配数组元素,则可以使用

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

The result in this case includes would be:

{ "result" : [ { "score" : 75.04996547553947 } ], "ok" : 1 }

这篇关于在mongodb中提取子数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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