增长一个集合用于储存股票交易记录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" ] }