Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb sum query

Tags:

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} 

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?

like image 217
user2597504 Avatar asked Sep 23 '13 22:09

user2597504


People also ask

How do I sum in MongoDB?

If used on a field that contains both numeric and non-numeric values, $sum ignores the non-numeric values and returns the sum of the numeric values. If used on a field that does not exist in any document in the collection, $sum returns 0 for that field. If all operands are non-numeric, $sum returns 0 .

How does MongoDB calculate sum of salary?

$sum operator returns the sum of all numeric values of documents in the collection in MongoDB. Above will create collection (or table) (if collection already exists it will insert documents in it). Step 2.1 - We will group employee by firstName and find sum of salary of each group.

What is aggregate sum?

a sum, mass, or assemblage of particulars; a total or gross amount: the aggregate of all past experience.


2 Answers

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 } } 
like image 180
jamshehan Avatar answered Oct 01 '22 01:10

jamshehan


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)); 
like image 42
yaya Avatar answered Oct 01 '22 01:10

yaya