1、MongoDB聚合管道(Aggregation Pilpeline)node
使用聚合管道能夠對集合中的文檔進行變換和組合。sql
主要功能:表的關聯查詢、數據統計mongodb
2、aggregate 管道操做符與表達式數據庫
管道操做符:nosql
sql 和 nosql 對比:ui
管道表達式:url
管道操做符做爲「鍵」,所對應的「值」叫作管道表達式。 spa
例如{$match:{status:"A"}}, $match 稱爲管道操做符, 而 status:"A"稱爲管道表達式,是管道操做符的操做數(Operand)。code
3、數據模擬:對象
db.order.insert({"order_id":"1","uid":10,"trade_no":"111","all_price":100,"all_num":2}) db.order.insert({"order_id":"2","uid":7,"trade_no":"222","all_price":90,"all_num":2}) db.order.insert({"order_id":"3","uid":9,"trade_no":"333","all_price":20,"all_num":6}) db.order_item.insert({"order_id":"1","title":"商品鼠標 1","price":50,num:1}) db.order_item.insert({"order_id":"1","title":"商品鍵盤 2","price":50,num:1}) db.order_item.insert({"order_id":"1","title":"商品鍵盤 3","price":0,num:1}) db.order_item.insert({"order_id":"2","title":"牛奶","price":50,num:1}) db.order_item.insert({"order_id":"2","title":"酸奶","price":40,num:1}) db.order_item.insert({"order_id":"3","title":"礦泉水","price":2,num:5}) db.order_item.insert({"order_id":"3","title":"毛巾","price":10,num:1})
4、$project
修改文檔的結構,能夠用來重命名、增長或者刪除文檔中的字段
例如:要求查找order只返回trade_no和all_price字段
db.order.aggregate([ { $project:{ trade_no:1, all_price:1 } } ])
5、$match
用於過濾文檔。相似where
db.order.aggregate([ { $project:{ trade_no:1, all_price:1 } }, { $match:{"all_price":{$gte:90}} } ])
6、$group
分組
統計每一個訂單的訂單數量, 按照訂單號分組
db.order_item.aggregate( [ { $group: {_id: "$order_id", total: {$sum: "$num"}} } ]
7、$sort
排序
-1:降序;1:升序
db.order.aggregate([ { $project:{ trade_no:1, all_price:1 } }, { $match:{"all_price":{$gte:90}} }, { $sort:{"all_price":-1} } ])
8、$limit
查詢前幾條
db.order.aggregate([ { $project:{ trade_no:1, all_price:1 } }, { $match:{"all_price":{$gte:90}} }, { $sort:{"all_price":-1} }, { $limit:1 } ])
9、$skip
跳過幾條
db.order.aggregate([ { $project:{ trade_no:1, all_price:1 } }, { $match:{"all_price":{$gte:90}} }, { $sort:{"all_price":-1} },{ $skip:1 } ])
10、$lookup
表關聯查詢
db.order.aggregate([ { $lookup: { from: "order_item", //關聯表 localField: "order_id", //主表的字段 foreignField: "order_id", //關聯表的字段 as: "items" //存儲的字段 } } ])
固然也可使用其餘操做符
db.order.aggregate([ { $lookup:{ from: "order_item", localField: "order_id", foreignField: "order_id", as: "items" } }, { $match:{"all_price":{$gte:90}} } ])
db.order.aggregate([ { $lookup: { from: "order_item", localField: "order_id", foreignField: "order_id", as: "items" } }, { $project:{ trade_no:1, all_price:1,items:1 } }, { $match:{"all_price":{$gte:90}} }, { $sort:{"all_price":-1}
}, ])
11、nodejs操做aggregate聚合管道
var MongoClient = require('mongodb').MongoClient; //定義鏈接數據庫的地址 const url = 'mongodb://localhost:27017/'; var dbName = 'eggcms'; //鏈接數據庫 MongoClient.connect(url,(err,client)=>{ if(err){ console.log('數據鏈接失敗'); return false; } let db=client.db(dbName); /*獲取db對象*/ db.collection("order").aggregate([ { $lookup: { from: "order_item", localField: "order_id", foreignField: "order_id", as: "items" } }, { $match:{"all_price":{$gte:90}} } ]).toArray(function(err,docs){ console.log(docs) }) })