增長一個集合用於儲存股票交易記錄shell
db.transactions.insert([ { symbol: "600519", qty: 100, price: 567.4, currency: "CNY" }, { symbol: "AMZN", qty: 1, price: 1377.5, currency: "USD" }, { symbol: "AAPL", qty: 2, price: 150.7, currency: "USD" } ])
按照交易貨幣來分組數組
db.transactions.aggregate([ { $group:{ _id:"$currency" } } ]) { "_id" : "CNY" } { "_id" : "USD" }
使用聚合操做符計算分組聚合值code
# totalQty 交易總股數 # totalNotional 交易總金額 # avgPrice 平均股價 # count 數量 # maxNotional 最大交易金額 # maxNotional 最小交易金額 db.transactions.aggregate([ { $group: { _id: "$currency", totalQty: { $sum: "$qty" }, totalNotional: { $sum: { $multiply: ["$price", "$qty"] } }, avgPrice: { $avg: "$price" }, count: { $sum: 1 }, maxNotional: { $max: { $multiply: [ "$price", "$qty" ] } }, minNotional: { $min: { $multiply: [ "$price", "$qty" ] } } } } ]) { "_id" : "CNY", "totalQty" : 100, "totalNotional" : 56740, "avgPrice" : 567.4, "count" : 1, "maxNotional" : 56740, "minNotional" : 56740 } { "_id" : "USD", "totalQty" : 3, "totalNotional" : 1678.9, "avgPrice" : 764.1, "count" : 2, "maxNotional" : 1377.5, "minNotional" : 301.4 }
使用聚合操做符計算全部文檔聚合值
將 _id 設置爲 null 便可ip
db.transactions.aggregate([ { $group: { _id: null, totalQty: {$sum: "$qty"}, totalNotional: {$sum: {$multiply: ["$price", "$qty"]}}, avgPrice: {$avg: "$price"}, count: {$sum: 1}, maxNotional: {$max: {$multiply: ["$price","$qty"]}}, minNotional: {$min: {$multiply: ["$price","$qty"]}} } } ]) { "_id" : null, "totalQty" : 103, "totalNotional" : 58418.9, "avgPrice" : 698.5333333333333, "count" : 3, "maxNotional" : 56740, "minNotional" : 301.4 }
使用聚合管道建立數組字段
將同一個組裏面的 symbol
字段,都 push
到一個新字段 symbols
中文檔
db.transactions.aggregate([ { $group: { _id: "$currency", symbols:{$push:"$symbol"} } } ]) { "_id" : "CNY", "symbols" : [ "600519" ] } { "_id" : "USD", "symbols" : [ "AMZN", "AAPL" ] }