MongoDB 中聚合統計計算--$SUM表達式


我們一般通過表達式$sum來計算總和。因為MongoDB的文檔有數組字段,所以可以簡單的將計算總和分成兩種:1,統計符合條件的所有文檔的某個字段的總和;2,統計每個文檔的數組字段里面的各個數據值的和。這兩種情況都可以通過$sum表達式來完成。以上兩種情況的聚合統計,分別對應與聚合框架中的 $group 操作步驟和 $project 操作步驟。

1.$group

直接看例子吧。

Case 1

測試集合mycol中的數據如下:

{
   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
}

現在我們通過以上集合計算每個作者所寫的文章數,使用aggregate()計算

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

查詢結果如下:

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

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

Case 2

統計每個作者被like的總和,計算表達式:

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

查詢結果如下;

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

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

Case 3

上面例子有些簡單,我們再豐富一下,測試集合sales的數據如下:

{ "_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") }

需要完成的目標是,基於日期分組,統計每天的銷售額,聚合公式為:

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

查詢結果是:

{ "_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 }

Case 4

上面的,可以看出$group,我們都使用了_id,使用了分組,那么如果,我們的需求不需要分組,應該怎么辦呢?

例如。我們現在要統計sales集合中一共賣出了多少件商品。

如果直接去掉group 階段的_id,如下:

db.sales.aggregate(
   [
     {
       $group:
         {
          
           totalAmount: { $sum: "$quantity" }
         }
     }
   ]
)
    

則報錯:

{
    "message" : "a group specification must include an _id",
    "ok" : 0,
    "code" : 15955,
    "codeName" : "Location15955",
    "name" : "MongoError"
}

我們還是需要添加上_id,但是可以添加個常量,及時根據常量分組,可以為  _id : "0" 可以是   _id : "a",   _id : "b",   還可以使_id : "x",   _id : "y" 等等。

例如:

 db.sales.aggregate(
   [
     {
       $group:
         {
          _id : "Total"
           totalAmount: { $sum: "$quantity" }
         }
     }
   ]
)

查詢結果為:

{
    "_id" : "Total",
    "totalAmount" : 28
}

2.$project階段

Case 5

假設存在一個 students 集合,其數據結構如下:

{ "_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 }

現在的需求是統計每個學生的 平常的測驗分數總和、實驗分數總和、期末其中分數總和。

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

其查詢輸出結果如下:

{ "_id" : 1, "quizTotal" : 23, "labTotal" : 13, "examTotal" : 155 }
{ "_id" : 2, "quizTotal" : 19, "labTotal" : 16, "examTotal" : 175 }
{ "_id" : 3, "quizTotal" : 14, "labTotal" : 11, "examTotal" : 148 }

 

 

參考文獻:

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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM