MongoDb 求和查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18969916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:26:00  来源:igfitidea点击:

MongoDb sum query

mongodb

提问by user2597504

For example I have the following data in MongoDB:

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

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

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?

现在我想查询“SUM 11 - 12 之间的传入数量”(结果应该是 500),我怎么能用 Mongo Shell 做到这一点?

回答by jamshehan

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

正如 lllovet 所建议的,聚合框架是要走的路。您的查询如下所示:

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

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 运算符来将生成的文档整形为仅包含总和,如下所示:

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

回答by yaya

Some examples if you use mongoose:

如果您使用mongoose 的一些示例:

  1. Calculate total sum of product prices :
  1. 计算产品价格的总和:
Products.aggregate([ { $match: {} }, { $group:
  { _id : null, sum : { $sum: "$Price" } }
}])
.then(res => console.log(res[0].sum));

( { $match: {} },can be removed. )

{ $match: {} },可以删除。)



  1. Sum of Product's prices in each category:
  1. 每个类别的产品价格总和:
Products.aggregate([{ $group:
  { _id : '$Category', sum : { $sum: "$Price" } }
}])
.then(res => console.log(res));