【问题标题】:extract subarray value in mongodb在mongodb中提取子数组值
【发布时间】:2012-11-07 07:30:07
【问题描述】:

这里是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 只显示测验分数?

【问题讨论】:

标签: mongodb mongo-shell


【解决方案1】:

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

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

$elemMatch投影

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

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

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

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

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

聚合框架

如果您想显示多个匹配值或重塑结果文档而不是返回完整匹配的数组元素,您可以使用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"
    }}
)

这种情况下的结果包括:

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

【讨论】:

  • Stennie 说的,他***建了数据库。
  • 通过 $elemMatch,如果我想要两个元素 type: 'exam'type : 'quiz' 怎么办?请回复
猜你喜欢
  • 2015-06-22
  • 2021-06-26
  • 2019-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多