關於mongodb的aggregate

  最近學習nodejs和mongo,當學到appregate的時候感到很困惑,通過一小段時間的學習,大概總結下所學的東西。css

 首先,先創建數據表html

 use userinfo node

 db //userinfoapp

 db.createCollection('user');學習

 首先要插入一些數據: htm

{
"_id" : ObjectId("588031590d6c56fe957a1d55"),
"name" : "lpc",
"title" : "html",
"price" : 300
}
{
"_id" : ObjectId("588031630d6c56fe957a1d56"),
"name" : "lpc",
"title" : "css",
"price" : 200
}
{
"_id" : ObjectId("5880316d0d6c56fe957a1d57"),
"name" : "yy",
"title" : "css",
"price" : 100
}it

接下來查詢咱們的數據大概看一下:io

db.user.find().pretty() //看到輸出結果ejs

 db.user.aggregate({$project:{username:'$name',userprice:'$price',usertitle:'$title'}},{$group:{_id:'$title',sum:{$sum:1},avg:{$avg:"$userprice"}}}).pretty()方法

大概解釋下這句話的意思:

aggregate的意思是聚合。咱們能夠經過這個方法來計算數據的和 最大最小值 平均值等

$project:能夠對結果集中的鍵重命名,控制鍵是否顯示(只要不寫進去就不會 顯示)

$project:{username:'$name',userprice:'$price',usertitle:'$title'}:這句話的意思就是把數據表中的name字段的名稱改變成‘username’

當只輸入¥project這一命令時,獲得的結果以下:

{ "_id" : ObjectId("588031590d6c56fe957a1d55"), "username" : "lpc", "usertitle" : "html", "userprice" : 300 }
{ "_id" : ObjectId("588031630d6c56fe957a1d56"), "username" : "lpc", "usertitle" : "css", "userprice" : 200 }
{ "_id" : ObjectId("5880316d0d6c56fe957a1d57"), "username" : "yy", "usertitle" : "css", "userprice" : 100 }

$group:分組,聚合,求和,平均數

_id(第一個感受必須填_id,要否則會報錯)

sum:{$sum:1} 根據_id求和,就是計算了title字段內容相同的和

avg:{$avg:"$userprice"} 根據userprice求平均值

輸出的結果爲:

{ "_id" : "css", "sum" : 2, "avg" : 150 }{ "_id" : "html", "sum" : 1, "avg" : 300 }

相關文章
相關標籤/搜索