map-reduce demo

db.orders.insertMany([
	{
     _id: ObjectId("10a8240b927d5d8b5891743c"),
     cust_id: "1",
     ord_date: new Date("Oct 04, 2012"),
     status: 'A',
     price: 25,
     items: [ { sku: "mmm", qty: 5, price: 2.5 },
              { sku: "nnn", qty: 5, price: 2.5 } ]
	},
    {
     _id: ObjectId("20a8240b927d5d8b5891743c"),
     cust_id: "1",
     ord_date: new Date("Oct 05, 2012"),
     status: 'A',
     price: 30,
     items: [ { sku: "mmm", qty: 15, price: 5 },
              { sku: "nnn", qty: 8, price: 7 } ]
	},
    {
     _id: ObjectId("30a8240b927d5d8b5891743c"),
     cust_id: "2",
     ord_date: new Date("Oct 01, 2012"),
     status: 'A',
     price: 30,
     items: [ { sku: "mmm", qty: 15, price: 3 },
              { sku: "nnn", qty: 8, price: 9 } ]
	}
])

根据cust_id求和 


var mapFunction1 = function() {
    emit(this.cust_id, this.price);
};


var reduceFunction1 = function(keyCustId, valuesPrices) {
     return Array.sum(valuesPrices);
};



db.orders.mapReduce(
    mapFunction1,
    reduceFunction1,
    { 
		out: "map_reduce_example" 
	}
)

计算item.sku计算item.qty平均值 



var mapFunction2 = function() {
	for (var idx = 0; idx < this.items.length; idx++) {
	   var key = this.items[idx].sku;
	   var value = {
					 count: 1,
					 qty: this.items[idx].qty
				   };
	   emit(key, value);
	}
};


var reduceFunction2 = function(keySKU, countObjVals) {
	reducedVal = { count: 0, qty: 0 };

	 for (var idx = 0; idx < countObjVals.length; idx++) {
		 reducedVal.count += countObjVals[idx].count;
		 reducedVal.qty += countObjVals[idx].qty;
	 }

	return reducedVal;
};



var finalizeFunction2 = function (key, reducedVal) {

   reducedVal.avg = reducedVal.qty/reducedVal.count;

   return reducedVal;

};


db.orders.mapReduce( 
	mapFunction2,
	reduceFunction2,
	 {
	   out: { merge: "map_reduce_example" },
	   query: { 
			ord_date:  { $gt: new Date('01/01/2012') }
			  },
	   finalize: finalizeFunction2
	 }
)
发布了505 篇原创文章 · 获赞 41 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/kq1983/article/details/103009170
今日推荐