Map-Reduce是一种计算模型,简单的说就是将大批量的工作(数据)分解(MAP)执行,然后再将结果合并成最终结果(REDUCE)。
MongoDB提供的Map-Reduce非常灵活,以下是常用样例:
1、mongodb mapreduce 查询集合中所有字段类型
db.runCommand({
"mapreduce" : "collectionName",
"map" : function () {
for (var key in this) {
emit(key, this);
}
},
"reduce" :function (key, values) {
var e = values[1][key];
var r = typeof e;
// js判断数据类型 方法二
// var a = Object.prototype.toString;
// var r = a.call(e);
return r;
},
"out": { inline : 1}
})
2、java 执行mongodb mapreduce 的例子
import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MapReduceCommand;
import com.mongodb.MapReduceOutput;
import com.mongodb.MongoClient;
/**
* Java + MongoDB MapReduce count()
*
*/
public class MapReduce {
public static void main(String[] args) {
// Connect to mongodb
MongoClient mongo = null;
try {
mongo = new MongoClient("localhost", 27017);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// get database
// if database doesn't exists, mongodb will create it for you
DB db = mongo.getDB("test");
// get collection
// if collection doesn't exists, mongodb will create it for you
DBCollection collection = db.getCollection("person");
String map ="function () {"+
"emit('size', {count:1});"+
"}";
String reduce = "function (key, values) { "+
" total = 0; "+
" for (var i in values) { "+
" total += values[i].count; "+
" } "+
" return {count:total} }";
MapReduceCommand cmd = new MapReduceCommand(collection, map, reduce,
null, MapReduceCommand.OutputType.INLINE, null);
MapReduceOutput out = collection.mapReduce(cmd);
for (DBObject o : out.results()) {
System.out.println(o.toString());
}
System.out.println("Done");
}
}