Wednesday, August 15, 2018

8. MongoDB : Aggregate, MapReduce & Group

8. MongoDB : Aggregate, MapReduce & Group


Aggregate ############################################


//Calculate the total transaction that customer did till now (consider only transaction >= 10000)
db.customer_info.aggregate([
                        {$match:{"transaction": {$gte:100000}}},    //consider only records gte=100000
{$group:{{_id: "Cust_Id", transaction: {$sum:"$amount"}}}},   //if Cust_Id is same add the transaction
{$sort:"trasaction":1}}]);


Another Eg:



db.items.count();   //6

db.items.distinct("item");   //[ "pen", "pencil", "books" ]

db.items.count({item: "pen"});  //2

MapReduce ###########################################

Map reduce: (Looks same as Aggregation, but this works parallely)
----------

var mapFunction = function() {emit(this.customer_name,this.amount)}; // customer_name, amount are fields in customer_info.

var reduceFunction = function(customer_name,arrayOfAmounts){
return Array.sum(arrayOfAmounts);
}

//using mapFunction and educeFunction => it generates mapReduce_result table with final o/p
db.customer_info.mapReduce(mapFunction,reduceFunction,{out: "mapReduce_result"});
show tables; //you see - mapReduce_result
db.mapReduce_result.find();  //o/p will be reduced o/p





Group ############################################

//display totalAmount of particular customer_name = "John"
db.customer_info.group({key: {"customer_name":1},      //group on customer_name
                        cond: {"customer_name": "John"},            //get only "John" customer
                        reduce:function(curr,result)                        //reduce: add all the amount
                                         {result.amount += curr.amount;}, 
                        intial: {amount:0}})


No comments:

Post a Comment