大家好,我是考100分的小小码 ,祝大家学习进步,加薪顺利呀。今天说一说MongoDB 聚合分类「建议收藏」,希望您对编程的造诣更进一步.
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"
}
])
代码100分
按照交易货币来分组
代码100分db.transactions.aggregate([
{
$group:{
_id:"$currency"
}
}
])
{ "_id" : "CNY" }
{ "_id" : "USD" }
使用聚合操作符计算分组聚合值
# 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 即可
代码100分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" ] }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
转载请注明出处: https://daima100.com/9133.html