Map Reduce is a data processing technique that condenses large volumes of data into aggregated results. MongoDB mapreduce command is provided to accomplish this task.

Map Reduce是一种数据处理技术,可将大量数据压缩为汇总结果。 提供MongoDB mapreduce命令来完成此任务。

Lets consider the following examples that demonstrates the mapreduce command usage.

让我们考虑以下示例,这些示例演示了mapreduce命令的用法。

Consider the car collection which contains the following documents;

考虑包含以下文件的汽车收藏;

>db.car.insert(
[
{car_id:"c1",name:"Audi",color:"Black",cno:"H110",mfdcountry:"Germany",speed:72,price:11.25}, {car_id:"c2",name:"Polo",color:"White",cno:"H111",mfdcountry:"Japan",speed:65,price:8.5}, {car_id:"c3",name:"Alto",color:"Silver",cno:"H112",mfdcountry:"India",speed:53,price:4.5},
{car_id:"c4",name:"Santro",color:"Grey",cno:"H113",mfdcountry:"Sweden",speed:89,price:3.5} ,
{car_id:"c5",name:"Zen",color:"Blue",cno:"H114",mfdcountry:"Denmark",speed:94,price:6.5} ] )
BulkWriteResult({"writeErrors" : [ ],"writeConcernErrors" : [ ],"nInserted" : 5,"nUpserted" : 0,"nMatched" : 0,"nModified" : 0,"nRemoved" : 0,"upserted" : [ ]
})
>

Now let’s write the map reduce function on car collection grouping by speed and categorizing them as overspeed cars.

现在,让我们通过速度并将其归类为超速汽车来对汽车收藏分组编写map reduce功能。

Define the map function as shown below

定义地图功能,如下所示

>var speedmap = function (){
var criteria;
if ( this.speed > 70 ) {
criteria = 'overspeed';
emit(criteria,this.speed);
}
};

This function categorizes the car as overspeed cars based on the speed. Here “this” refers to the current document for which map reducing has to be processed.

此功能根据速度将汽车分类为超速汽车。 这里的“ this”指的是当前文档,必须对其进行地图缩小处理。

Define the reduce function with arguments key and values to caluclate the average speed of the overspeed car as

使用参数键和值定义reduce函数,以计算超速汽车的平均速度为

>var avgspeed_reducemap = function(key, speed) {var total =0;for (var i = 0; i < speed.length; i++) { total = total+speed[i];}return total/speed.length;
};
>

Here the speed is summed up for all the cars through iterating the loop and the average speed is calculated as the sum of all the speed by the number of overspeed cars.

在这里,通过迭代循环将所有汽车的速度相加,并且将平均速度计算为所有速度与超速汽车数量的总和。

Invoke the map reduce function by calling the Map and Reduce functions on all the documents present in the car collection as;

通过以以下方式调用car集合中存在的所有文档上的Map and Reduce函数来调用map reduce函数;

>var ret = db.car.mapReduce(speedmap, avgspeed_reducemap, {out: "avgspeed"});

The output is fetched in a collection avgspeed.If this collection does not exist a new collection is created else the new contents are replaced.

输出在avgspeed集合中获取。如果此集合不存在,则会创建一个新集合,否则将替换新内容。

To see the documents invoke db.avgspeed.find()

要查看文档,请调用db.avgspeed.find()

Output:

输出:

{ "_id" : "overspeed", "value" : 85 }

The output states that there average speed of the overspeed cars is 85.

输出显示超速汽车的平均速度为85。

MongoDB Map Reduce Java示例 (MongoDB Map Reduce Java Example)

Below is the java program for above mongo shell example, note that it’s just showcasing the Map Reduce functions working. So make sure data is present in the collection for it to give desired result.

下面是上面mongo shell示例的Java程序,请注意,它只是展示了Map Reduce函数的工作方式。 因此,请确保数据存在于集合中以使其达到期望的结果。

package com.journaldev.mongodb;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;public class MongoDBMapReduce {public static void main(String[] args) throws UnknownHostException {// create an instance of client and establish the connectionMongoClient m1 = new MongoClient();// get the test db,use your ownDB db = m1.getDB("journaldev");// get the car collectionDBCollection coll = db.getCollection("car");// map function to categorize overspeed carsString carMap = "function (){" + "var criteria;"+ "if ( this.speed > 70 ) {" + "criteria = 'overspeed';"+ "emit(criteria,this.speed);" + "}" + "};";// reduce function to add all the speed and calculate the average speedString carReduce = "function(key, speed) {" + "var total =0;"+ "for (var i = 0; i < speed.length; i++) {"+ "total = total+speed[i];" + "}"+ "return total/speed.length;" + "};";// create the mapreduce command by calling map and reduce functionsMapReduceCommand mapcmd = new MapReduceCommand(coll, carMap, carReduce,null, MapReduceCommand.OutputType.INLINE, null);// invoke the mapreduce commandMapReduceOutput cars = coll.mapReduce(mapcmd);// print the average speed of carsfor (DBObject o : cars.results()) {System.out.println(o.toString());}}}

Above java program produces following output.

上面的java程序产生以下输出。

{ "_id" : "overspeed" , "value" : 85.0}

That’s all for a brief overview of Map Reduce functions in the MongoDB database, we will look other MongoDB features in coming posts.

以上就是对MongoDB数据库中Map Reduce函数的简要概述,我们将在以后的文章中介绍MongoDB的其他功能。

翻译自: https://www.journaldev.com/6322/mongodb-map-reduce-example-using-mongo-shell-and-java-driver

使用Mongo Shell和Java驱动程序的MongoDB Map Reduce示例相关推荐

  1. 使用Mongo Shell和Java驱动程序删除MongoDB的示例

    MongoDB remove method removes a single document or all the documents present in the collection or th ...

  2. 使用Shell和Java驱动程序的MongoDB身份验证配置示例

    Authentication enables user to verify identity before connecting to the database. At first, a user w ...

  3. MongoDB存在使用Mongo Shell和Java驱动程序的示例

    This checks the document for the existence of the fields in the specified collection. 这将检查文档中指定集合中是否 ...

  4. Java 8 Lambda表达式10个示例【存】

    PS:不能完全参考文章的代码,请参考这个文件http://files.cnblogs.com/files/AIThink/Test01.zip 在Java 8之前,如果想将行为传入函数,仅有的选择就是 ...

  5. Docker安装MoogoDB, 进入容器, mongo shell操作mongoDB

    安装MoogoDB, 进入容器, mongo shell操作mongoDB [ 包含 Docker-Compose方式.普通方式 ] 文章目录 安装MoogoDB, 进入容器, mongo shell ...

  6. MongoDB学习(五)使用Java驱动程序3.3操作MongoDB快速入门

    [引言] 毕竟现在MongoDB还是出于成长阶段,所以现在网上相关的资料很少,而且大部分还都是针对于MongoDB的老版本的.再加上MongoDB的频繁升级.重大更新等等,导致菜鸟学习的难度增大. 好 ...

  7. mongo shell连接到mongoDB及shell提示符下执行js脚本

    同mysql数据库类似,mongoDB也可通过mongo客户端连接到mongod服务器来进行绝大多数日常管理.这个命令行工具就是mongo,在mysql中则是mysql.通过mongo命令可以连接到本 ...

  8. java mongodb 关闭连接_如何在mongodb上使用java驱动程序保持连接池关闭?

    我正在从 java驱动程序2.12.3升级到3.3.0.奇怪的是,收集池似乎突然"起作用". 我的设置如下: Connection在主线程中建立: mongoClient = ne ...

  9. MongoDB学习笔记(3)- Mongo Shell 常用查询命令

    MongoDB学习笔记(3)- Mongo Shell 常用查询命令 本文所使用的MongoDB版本为 4.0.10 > db.version(); 4.0.10 一.find 命令进行简查询 ...

最新文章

  1. ABAP memory中的Export和Import
  2. 电子信息科学与技术计算机科学与技术会计学,我是本三学生 学的电子信息科学与技术专业 今年大三 从没接触过会计 想考注册会计师 可以么 ?...
  3. 福布斯评科技未来五大趋势:电脑消失融入生活时间
  4. Android之Http网络编程(四)
  5. 单例模式——Java
  6. springcloud config服务端配置(一)
  7. codevs——1044 拦截导弹(序列DP)
  8. 搞了很久终于突破了一点瓶颈,fighting!!!!!!!!!!!!!!!!
  9. Rust: 为什么同样的情况,有时不需要解引用?
  10. idea导入项目出现乱码
  11. matlab中划分训练集和测试集
  12. MBA-day4数学-十字交叉法
  13. elementui el-dialog 离顶部的位置_人眼距离屏幕合适位置该怎么算?
  14. 实习总结与收获(2021.6.7-2021.8.27)
  15. 无法完成压缩(zipped)文件来提取向导,怎么解决
  16. 1核2G3M,系统盘40G,流量500G/月,83一年
  17. RealView MDK开发工具
  18. 从键盘读入一个字符串,若遇到字母,则输出0;若遇到数字则输出1;否则不输出。例如:输入ab@12c,输出00110
  19. linux面试题_全网最新、最全Linux面试题(2020版)!
  20. 启动电脑时出现0xc000000f错误的解决办法

热门文章

  1. 语音特征参数MFCC的提取过程
  2. [转载] 在IPython中重新加载模块 importlib
  3. [转载] python---python中时间的应用(time模块)
  4. 作业1-3 求1+2!+3!+...+20!的和
  5. python基础7--socket
  6. hdu1247 字典树
  7. hdu 3461 Code Lock(并查集)2010 ACM-ICPC Multi-University Training Contest(3)
  8. nopcommerce笔记3 还可以控制什么
  9. ubuntu10.10和windows双系统启动顺序的修改(转)
  10. Oracle 单实例 迁移到 RAC 实例 -- 使用RMAN 异机恢复