美文网首页
MongoDB 的分类汇总功能

MongoDB 的分类汇总功能

作者: JohnYuCN | 来源:发表于2022-05-20 17:08 被阅读0次
原理图.png

演示代码:

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表
    }//
)

相关文章

网友评论

      本文标题:MongoDB 的分类汇总功能

      本文链接:https://www.haomeiwen.com/subject/zzwfprtx.html