MongoDb总和查询 [英] MongoDb sum query

查看:64
本文介绍了MongoDb总和查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我在MongoDB中具有以下数据:

For example I have the following data in MongoDB:

{ "_id" : ObjectId("524091f99c49c4c3f66b0e46"), "hour" : 10, "incoming", 100}
{ "_id" : ObjectId("5240a045dbeff33c7333aa51"), "hour" : 11, "incoming", 200}
{ "_id" : ObjectId("5240a2ecda0d37f35c618aca"), "hour" : 12, "incoming", 300}

现在,我想查询求和11到12之间的传入总数"(结果应该是500),如何使用Mongo Shell做到这一点?

Now I want to query "SUM the number of incoming between 11 - 12" (the result should be 500), how could I do this using Mongo Shell?

推荐答案

正如llovet所建议的,聚合框架是必经之路.这是您的查询内容:

As llovet suggested, the aggregation framework is the way to go. Here's what your query would look like:

db.CollectionNameGoesHere.aggregate({ $match: {
    $and: [
        { hour: { $gte: 11 } },
        { hour: { $lte: 12 } }
    ]
} },
{ $group: { _id : null, sum : { $sum: "$incoming" } } });

您还可以通过在管道的末尾添加$ project运算符来使生成的文档仅包含总和,如下所示:

You can also shape the resulting document to only contain the sum by adding a $project operator at the end of the pipeline, like so:

{ $project: { _id: 0, sum: 1 } }

这篇关于MongoDb总和查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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