演示代码:
let orders=[
{cust_id:"A123",amount:500,status:"A"},
{cust_id:"A123",amount:250,status:"A"},
{cust_id:"B212",amount:200,status:"A"},
{cust_id:"A123",amount:300,status:"D"},
]
db.orders.insertMany(orders)
//============基础汇总方式=================
db.orders.aggregate([
{$match:{status:"A"}},//进行筛选
{$group:{_id:'$cust_id',amount_totals:{$sum:'$amount'}}//按cust_id分类,对amount进行汇总
}])//返回结果,并显示
// =========mapReduce方式,更加通用============
db.orders.mapReduce(
function(){emit(this.cust_id,this.amount)},//map功能,返回按cust_id分类后的amount的数组
function(key,values){ //reduce功能,对amount数组进行汇总
return values.reduce((total,value)=>total+value,0)
},
{
query:{status:"A"},//筛选,此操作在map和reduce之前
out:'order_totals'//输出到order_totals表
}//
)
网友评论