首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在mongoDB中聚合集合中的每个项

问如何在mongoDB中聚合集合中的每个项
EN

Stack Overflow用户
提问于 2012-11-20 08:57:07
回答 1查看 572关注 0票数 0

MongoDB新手在这里...

当我在shell中执行db.students.find().pretty()时,我会从我的collection...like中得到一个很长的列表,所以..

代码语言:javascript
复制
{
    "_id" : 19,
    "name" : "Gisela Levin",
    "scores" : [
        {
            "type" : "exam",
            "score" : 44.51211101958831
        },
        {
            "type" : "quiz",
            "score" : 0.6578497966368002
        },
        {
            "type" : "homework",
            "score" : 93.36341655949683
        },
        {
            "type" : "homework",
            "score" : 49.43132782777443
        }
    ]
}

现在我已经有了大约100多个这样的…我需要在每个上面运行下面的代码…

代码语言:javascript
复制
lowest_hw_score = 

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

    // Expand the scores array into a stream of documents
    { $unwind: '$scores' },

    // Filter to 'homework' scores 
    { $match: {
        'scores.type': 'homework'
    }},

    // Sort in descending order
    { $sort: {
        'scores.score': 1
    }},

    { $limit: 1}
)

因此,我可以在每个结果上运行如下内容

代码语言:javascript
复制
for item in lowest_hw_score:
    print lowest_hw_score

现在,"lowest_score“只在一个项目上有效,我要在collection...how中的所有项目上运行它,我要这样做吗?

EN

回答 1

Stack Overflow用户

发布于 2012-11-20 09:28:33

代码语言:javascript
复制
> db.students.aggregate(  
{ $match :  { 'scores.type': 'homework' } },
{ $unwind:  "$scores" },
{ $match:{"scores.type":"homework"} }, 
{ $group: { 
    _id : "$_id", 
   maxScore : { $max : "$scores.score"}, 
   minScore: { $min:"$scores.score"} 
  }
});

您实际上并不需要第一个$match,但是如果"scores.type“被编入索引,这意味着它将在解开分数之前被使用。(我不相信在$unwind之后,mongo将能够使用索引。)

结果:

代码语言:javascript
复制
{
"result" : [
    {
        "_id" : 19,
        "maxScore" : 93.36341655949683,
        "minScore" : 49.43132782777443
    }
],
"ok" : 1
}

编辑:在mongo shell中测试和更新

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13465062

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档