Aggregate statistical calculations in MongoDB $SUM expression

  • 2020-12-19 21:16:07
  • OfStack

We usually calculate the sum through the expression $sum. Because MongoDB's documents have array fields, it is easy to divide the calculated sum into two categories:

1. Count the sum of a certain field of all documents that meet the conditions;

2. Count the sum of each data value in the array field of each document. Both cases can be done using the $sum expression.

The aggregate statistics of the above two cases correspond to those in the aggregate framework respectively $group Operation steps and $project Operating steps.

1.$group

So let's go straight to the example.

Case 1

The data in the test set mycol is as follows:


{
 title: 'MongoDB Overview', 
 description: 'MongoDB is no sql database',
 by_user: 'runoob.com',
 url: 'http://www.runoob.com',
 tags: ['mongodb', 'database', 'NoSQL'],
 likes: 100
},
{
 title: 'NoSQL Overview', 
 description: 'No sql database is very fast',
 by_user: 'runoob.com',
 url: 'http://www.runoob.com',
 tags: ['mongodb', 'database', 'NoSQL'],
 likes: 10
},
{
 title: 'Neo4j Overview', 
 description: 'Neo4j is no sql database',
 by_user: 'Neo4j',
 url: 'http://www.neo4j.com',
 tags: ['neo4j', 'database', 'NoSQL'],
 likes: 750
}

Now let's calculate the number of articles written by each author using the above set, using aggregate()


db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])

The query results are as follows:


/* 1 */
{
 "_id" : "Neo4j",
 "num_tutorial" : 1
},

/* 2 */
{
 "_id" : "runoob.com",
 "num_tutorial" : 2
}

Case 2

Count the sum of each author by like, calculate the expression:


db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$likes"}}}])

The query results are as follows;


/* 1 */
{
 "_id" : "Neo4j",
 "num_tutorial" : 750
},

/* 2 */
{
 "_id" : "runoob.com",
 "num_tutorial" : 110
}

Case 3

The above example is a little simple. Let's enrich 1 more. The data of test set sales is as follows:


{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:00:00Z") }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-02-03T09:00:00Z") }
{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-03T09:05:00Z") }
{ "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-02-15T08:00:00Z") }
{ "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-15T09:05:00Z") }

The goal to be achieved is to group the daily sales based on the date, and the aggregate formula is as follows:


db.sales.aggregate(
 [
  {
  $group:
   {
   _id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } },
   totalAmount: { $sum: { $multiply: [ "$price", "$quantity" ] } },
   count: { $sum: 1 }
   }
  }
 ]
)

The query results are:


{ "_id" : { "day" : 46, "year" : 2014 }, "totalAmount" : 150, "count" : 2 }
{ "_id" : { "day" : 34, "year" : 2014 }, "totalAmount" : 45, "count" : 2 }
{ "_id" : { "day" : 1, "year" : 2014 }, "totalAmount" : 20, "count" : 1 }

2. $project stage

Case 4

Suppose there is an students set, whose data structure is as follows:


{ "_id": 1, "quizzes": [ 10, 6, 7 ], "labs": [ 5, 8 ], "final": 80, "midterm": 75 }
{ "_id": 2, "quizzes": [ 9, 10 ], "labs": [ 8, 8 ], "final": 95, "midterm": 80 }
{ "_id": 3, "quizzes": [ 4, 5, 5 ], "labs": [ 6, 5 ], "final": 78, "midterm": 70 }

The current requirement is to calculate the sum of each student's ordinary test scores, experimental scores and final scores.


db.students.aggregate([
 {
  $project: {
  quizTotal: { $sum: "$quizzes"},
  labTotal: { $sum: "$labs" },
  examTotal: { $sum: [ "$final", "$midterm" ] }
  }
 }
])

The query output results are as follows:


db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
0

References:

https://www.runoob.com/mongodb/mongodb-aggregate.html

https://docs.mongodb.com/manual/reference/operator/aggregation/sum/index.html

conclusion


Related articles: