Home Database Mysql Tutorial Mongodb中数据聚合之MapReduce

Mongodb中数据聚合之MapReduce

Jun 07, 2016 pm 02:50 PM
mapreduce mongodb data polymerization

Mongodb是针对大数据量环境下诞生的用于保存大数据量的非关系型数据库,针对大量的数据,如何进行统计操作至关重要,那么如何从Mongodb中统计一些数据呢? 在Mongodb中,给我们提供了三种用于数据聚合的方式: (1)简单的用户聚合函数; (2)使用aggregate

Mongodb是针对大数据量环境下诞生的用于保存大数据量的非关系型数据库,针对大量的数据,如何进行统计操作至关重要,那么如何从Mongodb中统计一些数据呢?

在Mongodb中,给我们提供了三种用于数据聚合的方式:

(1)简单的用户聚合函数;

(2)使用aggregate进行统计;

(3)使用mapReduce进行统计;

今天我们首先来讲讲mapReduce是如何统计,在后续的文章中,将另起文章进行相关说明。

MapReduce是啥呢?以我的理解,其实就是对集合中的各个满足条件的文档进行预处理,整理出想要的数据然后进行统计得到最终的统计结果。其中map函数用于对集合中的各个满足条件的文档进行预处理,整理出想要的数据。Reduce函数用于对整理出的数据进行处理得到统计结果。Map函数和Reduce函数都是JavaScript函数。

首先,我们先构造一个测试数据集test,使用js脚本往集合中随机插入一组数据,每条记录是哪个人花了多少钱买了什么东西。具体脚本test1.js如下:

<span style="font-size:18px;">for( var i=0; i=3 && rID=5 && rID</span>
Copy after login

接下来我们通过在控制台执行脚本来向数据库插入具体的数据,具体执行指令如下:

<span style="font-size:18px;">mongo 127.0.0.1:27017/test J:/test1.js</span>
Copy after login

执行之后,通过MongoVUE来查看下具体的数据,如下所示,数据已经插入到集合中了:


接下来,我们可以做几个简单的统计操作了。

(1)统计不同用户都买了多少个商品?编写js脚本test2.js,将结果保存到statis1集合中。

<span style="font-size:18px;"><span style="font-size:18px;">map=function(){
	emit(this.user,1);
}

reduce=function(key, values){
	var count = 0;
	values.forEach(function(val){count += val});
	return count;
}

db.test.mapReduce(map, reduce, {out:"statics1"});</span></span>
Copy after login

按照刚才执行脚本的方式执行test2.js,并查看数据:


从数据库就可以直观看到统计数据了,若想查看某个人如majing购买了多少个商品,直接使用

<span style="font-size:18px;"><span style="font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:18px;">db.statics1.find({"_id":"majing"});</span></span></span>
Copy after login


(2)统计每个用户购买的每个商品的数量情况

脚本test3.js如下所示:

<span style="font-size:18px;"><span style="font-size:18px;">map=function(){
	emit({user:this.user,sku:this.sku},1);
}

reduce=function(key, values){
	var count = 0;
	values.forEach(function(val){count += val});
	return count;
}

db.test.mapReduce(map, reduce, {out:"statics2"});</span></span>
Copy after login


按照刚才执行脚本的方式执行test3.js,并查看数据:


总共返回了10条记录。此时如果我们想查找某个用户购买商品的情况,可以使用下面的查询方法:

<span style="font-size:18px;"><span style="font-size:18px;">db.statics2.find({"_id.user":"majing"});</span></span>
Copy after login



如果我们想查找某个用户购买某个商品的情况,可以使用下面的查询方法:


(3)统计每个用户购买商品的总量及花费的总金额

脚本test4.js如下所示:

<span style="font-size:18px;"><span style="font-size:18px;">map=function(){
	emit({user:this.user},{totalprice:this.price,count:1});
}

reduce=function(key, values){
	var res = {totalprice:0.00,count:1};
	values.forEach(function(val){res.totalprice += val.totalprice;res.count+=val.count;});
	return res;
}

db.test.mapReduce(map, reduce, {out:"statics3"});</span></span>
Copy after login

按照刚才执行脚本的方式执行test4.js,并查看数据:


(4)统计每个用户购买商品的平均价钱

在这个情景下,我们需要用到说道mapReduce里的另一个参数finalize,该参数是一个javascript脚本函数,用于对reduce后的集合进行一个后期处理操作。

执行脚本test5.js,具体如下所示:


<span style="font-size:18px;"><span style="font-size:18px;">map=function(){
	emit({user:this.user},{totalprice:this.price,count:1});
}

reduce=function(key, values){
	var res = {totalprice:0.00,count:1,average:0};
	values.forEach(function(val){res.totalprice += val.totalprice;res.count+=val.count;});
	return res;
}

finalizeFunc=function(key,reduceResult){
	reduceResult.totalprice=(reduceResult.totalprice).toFixed(2);
	reduceResult.average=(reduceResult.totalprice/reduceResult.count).toFixed(2);
	return reduceResult;
}

db.test.mapReduce(map, reduce, {out:"statics4",finalize:finalizeFunc});</span></span>
Copy after login

执行之后查看得到的数据,具体如下所示,显示了总价钱,商品数量和商品单价。


如果想查找某个人的,可以和上面的查询方法一样,使用find()方法进行查询:

<span style="font-size:18px;"><span style="font-size:18px;">db.statics4.find({"_id.user":"majing"});</span></span>
Copy after login

以上通过4个简单的例子对Mongodb中的MapReduce进行了简单的说明,当然MapReduce功能很强大,大家如果想知道其他高级的使用方法,可以到Mongodb的官网进行查阅和学习,网址为 https://docs.mongodb.com/manual/reference/method/db.collection.mapReduce/ ,谢谢。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

70B model generates 1,000 tokens in seconds, code rewriting surpasses GPT-4o, from the Cursor team, a code artifact invested by OpenAI 70B model generates 1,000 tokens in seconds, code rewriting surpasses GPT-4o, from the Cursor team, a code artifact invested by OpenAI Jun 13, 2024 pm 03:47 PM

70B model, 1000 tokens can be generated in seconds, which translates into nearly 4000 characters! The researchers fine-tuned Llama3 and introduced an acceleration algorithm. Compared with the native version, the speed is 13 times faster! Not only is it fast, its performance on code rewriting tasks even surpasses GPT-4o. This achievement comes from anysphere, the team behind the popular AI programming artifact Cursor, and OpenAI also participated in the investment. You must know that on Groq, a well-known fast inference acceleration framework, the inference speed of 70BLlama3 is only more than 300 tokens per second. With the speed of Cursor, it can be said that it achieves near-instant complete code file editing. Some people call it a good guy, if you put Curs

China Mobile: Humanity is entering the fourth industrial revolution and officially announced 'three plans” China Mobile: Humanity is entering the fourth industrial revolution and officially announced 'three plans” Jun 27, 2024 am 10:29 AM

According to news on June 26, at the opening ceremony of the 2024 World Mobile Communications Conference Shanghai (MWC Shanghai), China Mobile Chairman Yang Jie delivered a speech. He said that currently, human society is entering the fourth industrial revolution, which is dominated by information and deeply integrated with information and energy, that is, the "digital intelligence revolution", and the formation of new productive forces is accelerating. Yang Jie believes that from the "mechanization revolution" driven by steam engines, to the "electrification revolution" driven by electricity, internal combustion engines, etc., to the "information revolution" driven by computers and the Internet, each round of industrial revolution is based on "information and "Energy" is the main line, bringing productivity development

The inside story of Google's search algorithm was revealed, and 2,500 pages of documents were leaked with real names! Search Ranking Lies Exposed The inside story of Google's search algorithm was revealed, and 2,500 pages of documents were leaked with real names! Search Ranking Lies Exposed Jun 11, 2024 am 09:14 AM

Recently, 2,500 pages of internal Google documents were leaked, revealing how search, "the Internet's most powerful arbiter," operates. SparkToro's co-founder and CEO is an anonymous person. He published a blog post on his personal website, claiming that "an anonymous person shared with me thousands of pages of leaked Google Search API documentation that everyone in SEO should read." Go to them! "For many years, RandFishkin has been the top spokesperson in the field of SEO (Search Engine Optimization, search engine optimization), and he proposed the concept of "website authority" (DomainRating). Since he is highly respected in this field, RandFishkin

How to configure MongoDB automatic expansion on Debian How to configure MongoDB automatic expansion on Debian Apr 02, 2025 am 07:36 AM

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

How to ensure high availability of MongoDB on Debian How to ensure high availability of MongoDB on Debian Apr 02, 2025 am 07:21 AM

This article describes how to build a highly available MongoDB database on a Debian system. We will explore multiple ways to ensure data security and services continue to operate. Key strategy: ReplicaSet: ReplicaSet: Use replicasets to achieve data redundancy and automatic failover. When a master node fails, the replica set will automatically elect a new master node to ensure the continuous availability of the service. Data backup and recovery: Regularly use the mongodump command to backup the database and formulate effective recovery strategies to deal with the risk of data loss. Monitoring and Alarms: Deploy monitoring tools (such as Prometheus, Grafana) to monitor the running status of MongoDB in real time, and

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Apr 18, 2025 am 11:48 AM

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

What is the CentOS MongoDB backup strategy? What is the CentOS MongoDB backup strategy? Apr 14, 2025 pm 04:51 PM

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

See all articles