76

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}

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?

user2597504
  • 1,503
  • 3
  • 23
  • 32
  • 5
    Check out MongoDB's [aggregation framework](http://docs.mongodb.org/manual/reference/aggregation/). In particular, take a look at [`$match`](http://docs.mongodb.org/manual/reference/aggregation/match/#pipe._S_match), [`$group`](http://docs.mongodb.org/manual/reference/aggregation/group/#pipe._S_group), and [`$sum`](http://docs.mongodb.org/manual/reference/aggregation/sum/#grp._S_sum). – llovett Sep 23 '13 at 22:29

2 Answers2

126

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" } } });

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 } }
jamshehan
  • 1,481
  • 1
  • 10
  • 9
9

Some examples if you use mongoose:

  1. Calculate total sum of product prices :
Products.aggregate([ { $match: {} }, { $group:
  { _id : null, sum : { $sum: "$Price" } }
}])
.then(res => console.log(res[0].sum));

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


  1. Sum of Product's prices in each category:
Products.aggregate([{ $group:
  { _id : '$Category', sum : { $sum: "$Price" } }
}])
.then(res => console.log(res));
yaya
  • 7,675
  • 1
  • 39
  • 38