Map-reduce是一种数据处理范例,用于将大量数据压缩为有用的聚合结果。
让我们创建一个包含文档的集合-
> db.demo280.insertOne({"CustomerName":"Chris","isMarried":true}); { "acknowledged" : true, "insertedId" : ObjectId("5e49116edd099650a5401a62") } > db.demo280.insertOne({"CustomerName":"Mike","isMarried":false}); { "acknowledged" : true, "insertedId" : ObjectId("5e491170dd099650a5401a63") } > db.demo280.insertOne({"CustomerName":"David","isMarried":false}); { "acknowledged" : true, "insertedId" : ObjectId("5e491170dd099650a5401a64") } > db.demo280.insertOne({"CustomerName":"Bob","isMarried":true}); { "acknowledged" : true, "insertedId" : ObjectId("5e491171dd099650a5401a65") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo280.find();
这将产生以下输出-
{ "_id" : ObjectId("5e49116edd099650a5401a62"), "CustomerName" : "Chris", "isMarried" : true } { "_id" : ObjectId("5e491170dd099650a5401a63"), "CustomerName" : "Mike", "isMarried" : false } { "_id" : ObjectId("5e491170dd099650a5401a64"), "CustomerName" : "David", "isMarried" : false } { "_id" : ObjectId("5e491171dd099650a5401a65"), "CustomerName" : "Bob", "isMarried" : true }
以下是实现Mongo DB mapreduce的查询-
> db.demo280.mapReduce( ... function() { emit(this.isMarried,true); }, ... ... function(key, values) {return Array.sum(values)}, { ... query:{isMarried:true}, ... out:"Output" ... } ...)
这将产生以下输出,显示总共2个与查询匹配的文档(输入:2个),并发出2个结果(发出:2个)-
{ "result" : "Output", "timeMillis" : 1241, "counts" : { "input" : 2, "emit" : 2, "reduce" : 1, "output" : 1 }, "ok" : 1 }