1. 程式人生 > >MongoDB——》聚合查詢(project、match、limit、skip、unwind、group、sort)

MongoDB——》聚合查詢(project、match、limit、skip、unwind、group、sort)

版權宣告:本文為博主原創文章,無需授權即可轉載,甚至無需保留以上版權宣告,轉載時請務必註明作者。
https://blog.csdn.net/weixin_43453386/article/details/85065043

MongoDB——》聚合查詢(project、match、group、limit、skip、unwind、sort)

kip、unwind、sort))

db:當前資料庫名
test:當前集合名

test集合中的資料如下圖所示:
在這裡插入圖片描述

一、聚合

1、聚合

2、聚合運算子

序號 運算子 說明
1 $add 計算數值的總和
2 $divide 給定兩個數值,用第一個數除以第二個數
3 $mod 取模。
4 $multiply 計算數值陣列的乘積
5 $subtract 給定兩個數值,用第一個數減去第二個數
6 $concat 連線兩個字串
7 $strcasecmp 比較兩個字串並返回一個整數來反應比較結果
8 $substr 返回字串的一部分
9 $toLower 將字串轉化為小寫
10 $toUpper 將字串轉化為大寫

二、聚合運算子

1、$project

  • 修改輸入文件的結構
  • 重新命名、增加或刪除域
  • 建立計算結果以及巢狀文件

1) 例:獲取test集合的weight欄位及name欄位(_id顯示)

db.test.aggregate(
    { $project : {
        weight: 1 ,
        name : 1 
    }}
 );

在這裡插入圖片描述

2) 例:獲取test集合的weight欄位及name欄位(_id不顯示)

db.test.aggregate(
    { $project : {
         _id : 0 ,
        weight: 1 ,
        name : 1 
    }}
 );

在這裡插入圖片描述

3) 例:使用$add給weight欄位的值加10,然後將結果賦值給一個新的欄位:newWeight

db.test.aggregate(
    { $project : {
         _id : 0 ,
        name : 1  ,
        weight : 1 ,
        newWeight : { $add:["$weight", 10] }
    }}
 );

在這裡插入圖片描述

4) 例:把weight重新命名為newWeight

db.test.aggregate(
    { $project : {
         _id : 0 ,
        name : 1  ,
        weight : 1 ,
        newWeight : "$weight"
    }}
 );
    

在這裡插入圖片描述

2、$match

  • 用於過濾資料,只輸出符合條件的文件
  • 在$match中不能使用$geoNear地理空間操作符及$where表示式操作符

1) 例:獲取test集合的weight>=0.5且weight<=1

db.test.aggregate( {
    $match : 
        { weight : 
            { $gte : 0.5, $lte : 1 } 
        }
});

或者

db.test.aggregate([
    {$match : 
        { weight : 
            { $gte : 0.5, $lte : 1 } 
        }
    }
]);

在這裡插入圖片描述

2) 例:獲取test集合的weight>=0.5且weight<=1,然後將符合條件的記錄送到下一階段$group管道操作符進行處理

db.test.aggregate([
    {$match : 
        { weight : 
            { $gte : 0.5, $lte : 1 } 
        }
    },
    { $group: 
        { _id: null, 
          count: { $sum: 1 } 
        } 
    }
]);

在這裡插入圖片描述

3、$group

  • 將集合中的文件分組,可用於統計結果
  • 在$match中不能使用$geoNear地理空間操作符及$where表示式操作符

1) 例:獲取test集合的weight>=0.5且weight<=1,然後將符合條件的記錄送到下一階段$group管道操作符進行處理

db.test.aggregate([
    {$match : 
        { weight : 
            { $gte : 0.5, $lte : 1 } 
        }
    },
    { $group: 
        { _id: null, 
          count: { $sum: 1 } 
        } 
    }
]);

在這裡插入圖片描述

4、$limit

  • $limit會接受一個數字n,返回結果集中的前n個文件

1) 例:查詢5條文件記錄

db.test.aggregate({ $limit : 5 });

在這裡插入圖片描述

5、$skip

  • $skip接受一個數字n,丟棄結果集中的前n個文件
  • 限定可以傳遞到聚合操作的下一個管道中的文件數量

1) 例:獲取test集合中第5條資料之後的資料

db.test.aggregate({ $skip: 5 });

在這裡插入圖片描述