語法:
db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
> db.demo.find()
{ "_id" : ObjectId("5e79a57ba3edd4aa4ff0c2c3"), "name" : "hisName", "age" : 20, "hobby" : [ "drawing", "run" ] }
{ "_id" : ObjectId("5e79a878a3edd4aa4ff0c2c4"), "name" : "yourName", "age" : "30", "hobby" : [ "drawing", "run" ] }
>
> db.demo.aggregate([{$group:{_id:"$name",num_tutorial:{$sum:1}}}])
{ "_id" : "yourName", "num_tutorial" : 1 }
{ "_id" : "hisName", "num_tutorial" : 1 }
>
類似sql語句:
select name as _id, count(*) as num_tutorial from demo group by name
表達式 | 描述 | 實例 |
---|---|---|
$sum | 計算總和。 | db.mycol.aggregate([{KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "name", num_tutorial : {likes"}}}]) |
$avg | 計算平均值 | db.mycol.aggregate([{KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "name", num_tutorial : {likes"}}}]) |
$min | 獲取集合中所有文檔對應值得最小值。 | db.mycol.aggregate([{KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "name", num_tutorial : {likes"}}}]) |
$max | 獲取集合中所有文檔對應值得最大值。 | db.mycol.aggregate([{KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "name", num_tutorial : {likes"}}}]) |
$push | 在結果文檔中插入值到一個數組中。 | db.mycol.aggregate([{KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "name", url : {url"}}}]) |
$addToSet | 在結果文檔中插入值到一個數組中,但不創建副本。 | db.mycol.aggregate([{KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "name", url : {url"}}}]) |
$first | 根據資源文檔的排序獲取第一個文檔數據。 | db.mycol.aggregate([{KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "name", first_url : {url"}}}]) |
$last | 根據資源文檔的排序獲取最後一個文檔數據 | db.mycol.aggregate([{KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "name", last_url : {url"}}}]) |
-
聚合框架中常用的幾個操作:
- $project:修改輸入文檔的結構。可以用來重命名、增加或刪除域,也可以用於創建計算結果以及嵌套文檔。
- **match使用MongoDB的標準查詢操作。
- $limit**:用來限制MongoDB聚合管道返回的文檔數。
- $skip:在聚合管道中跳過指定數量的文檔,並返回餘下的文檔。
- $unwind:將文檔中的某一個數組類型字段拆分成多條,每條包含數組中的一個值。
- $group:將集合中的文檔分組,可用於統計結果。
- $sort:將輸入文檔排序後輸出。
- $geoNear:輸出接近某一地理位置的有序文檔。
-
時間關鍵字如下:
- $dayOfYear: 返回該日期是這一年的第幾天(全年 366 天)。
- $dayOfMonth: 返回該日期是這一個月的第幾天(1到31)。
- $dayOfWeek: 返回的是這個周的星期幾(1:星期日,7:星期六)。
- $year: 返回該日期的年份部分。
- $month: 返回該日期的月份部分( 1 到 12)。
- $week: 返回該日期是所在年的第幾個星期( 0 到 53)。
- $hour: 返回該日期的小時部分。
- $minute: 返回該日期的分鐘部分。
- $second: 返回該日期的秒部分(以0到59之間的數字形式返回日期的第二部分,但可以是60來計算閏秒)。
- $millisecond:返回該日期的毫秒部分( 0 到 999)。
- $dateToString: { $dateToString: { format: , date: } }。
管道操作符實例
1、$project實例
db.article.aggregate(
{ $project : {
title : 1 ,
author : 1 ,
}}
);
這樣的話結果中就只還有_id,tilte和author三個字段了,默認情況下_id字段是被包含的,如果要想不包含_id話可以這樣:
db.article.aggregate(
{ $project : {
_id : 0 ,
title : 1 ,
author : 1
}});
2.$match實例
db.articles.aggregate( [
{ $match : { score : { $gt : 70, $lte : 90 } } },
{ $group: { _id: null, count: { $sum: 1 } } }
] );
group管道操作符進行處理。
3.$skip實例
db.article.aggregate(
{ $skip : 5 });
經過$skip管道操作符處理後,前五個文檔被"過濾"掉。