Home Database Mysql Tutorial MongoDB学习之旅十二:MongoDBMapReduce

MongoDB学习之旅十二:MongoDBMapReduce

Jun 07, 2016 pm 03:55 PM
mongodb study

MongDB的MapReduce相当于MySQL中的group by,所以在MongoDB上使用Map/Reduce进行并行统计很容易。 使用MapReduce要实现两个函数Map函数和Reduce函数,Map函数调用emit(key,value),遍历collection中的所有记录,将key和value传递给Reduce函数进行处理。Map函

MongDB的MapReduce相当于MySQL中的“group by”,所以在MongoDB上使用Map/Reduce进行并行“统计”很容易。

使用MapReduce要实现两个函数Map函数和Reduce函数,Map函数调用emit(key,value),遍历collection中的所有记录,将key和value传递给Reduce函数进行处理。Map函数和Reduce函数可以使用JS来实现,可以通过db.runCommand或mapReduce命令来执行一个MapReduce操作。

示例shell

db.runCommand(
{ mapreduce : <collection>,
map : <mapfunction>,
reduce : <reducefunction>
[, query : <query filter object>]
[, sort : <sorts the input objects using this key. Useful for optimization, like sorting by the
emit key for fewer reduces>]
[, limit : <number of objects to return from collection>]
[, out : <see output options below>]
[, keeptemp: <true|false>]
[, finalize : <finalizefunction>]
[, scope : <object where fields go into javascript global scope >]
[, verbose : true]
}
);
Copy after login
参数说明:
 mapreduce: 要操作的目标集合。
 map: 映射函数 (生成键值对序列,作为 reduce 函数参数)。
 reduce: 统计函数。
 query: 目标记录过滤。
 sort: 目标记录排序。
 limit: 限制目标记录数量。
 out: 统计结果存放集合 (不指定则使用临时集合,在客户端断开后自动删除)。
 keeptemp: 是否保留临时集合。
 finalize: 最终处理函数 (对 reduce 返回结果进行最终整理后存入结果集合)。
 scope: 向 map、reduce、finalize 导入外部变量。
 verbose: 显示详细的时间统计信息。

下面我们准备数据以备后面示例所需

> db.students.insert({classid:1, age:14, name:&#39;Tom&#39;})
> db.students.insert({classid:1, age:12, name:&#39;Jacky&#39;})
> db.students.insert({classid:2, age:16, name:&#39;Lily&#39;})
> db.students.insert({classid:2, age:9, name:&#39;Tony&#39;})
> db.students.insert({classid:2, age:19, name:&#39;Harry&#39;})
> db.students.insert({classid:2, age:13, name:&#39;Vincent&#39;})
> db.students.insert({classid:1, age:14, name:&#39;Bill&#39;})
> db.students.insert({classid:2, age:17, name:&#39;Bruce&#39;})
>
Copy after login
现在我们演示如何统计1班和2班的学生数量

Map 函数必须调用 emit(key, value) 返回键值对,使用 this 访问当前待处理的 Document。

这里this一定不能忘了!!!

> m = function() { emit(this.classid, 1) }
function () {
emit(this.classid, 1);
}
>
Copy after login
value 可以使用 JSON Object 传递 (支持多个属性值)。例如:
emit(this.classid, {count:1})
Reduce 函数接收的参数类似 Group 效果,将 Map 返回的键值序列组合成 { key, [value1,value2, value3, value...] } 传递给 reduce。
> r = function(key, values) {
... var x = 0;
... values.forEach(function(v) { x += v });
... return x;
... }
function (key, values) {
var x = 0;
values.forEach(function (v) {x += v;});
return x;
}
>
Copy after login
Reduce 函数对这些 values 进行 "统计" 操作,返回结果可以使用 JSON Object。

结果如下:

> res = db.runCommand({
... mapreduce:"students",
... map:m,
... reduce:r,
... out:"students_res"
... });
{
"result" : "students_res",
"timeMillis" : 1587,
"counts" : {
"input" : 8,
"emit" : 8,
"output" : 2
},
"ok" : 1
}
> db.students_res.find()
{ "_id" : 1, "value" : 3 }
{ "_id" : 2, "value" : 5 }
>
Copy after login
mapReduce() 将结果存储在 "students_res" 表中。

利用 finalize() 我们可以对 reduce() 的结果做进一步处理。

> f = function(key, value) { return {classid:key, count:value}; }
function (key, value) {
return {classid:key, count:value};
}
>
Copy after login
我们再重新计算一次,看看返回的结果:
> res = db.runCommand({
... mapreduce:"students",
... map:m,
... reduce:r,
... out:"students_res",
... finalize:f
... });
{
"result" : "students_res",
"timeMillis" : 804,
"counts" : {
"input" : 8,
"emit" : 8,
"output" : 2
},
"ok" : 1
}
> db.students_res.find()
{ "_id" : 1, "value" : { "classid" : 1, "count" : 3 } }
{ "_id" : 2, "value" : { "classid" : 2, "count" : 5 } }
>
Copy after login
列名变与 “classid”和”count”了,这样的列表更容易理解。

我们还可以添加更多的控制细节。

> res = db.runCommand({
... mapreduce:"students",
... map:m,
... reduce:r,
... out:"students_res",
... finalize:f,
... query:{age:{$lt:10}}
... });
{
"result" : "students_res",
"timeMillis" : 358,
"counts" : {
"input" : 1,
"emit" : 1,
"output" : 1
},
"ok" : 1
}
> db.students_res.find();
{ "_id" : 2, "value" : { "classid" : 2, "count" : 1 } }
>
Copy after login
可以看到先进行了过滤,只取age
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Which version is generally used for mongodb? Which version is generally used for mongodb? Apr 07, 2024 pm 05:48 PM

It is recommended to use the latest version of MongoDB (currently 5.0) as it provides the latest features and improvements. When selecting a version, you need to consider functional requirements, compatibility, stability, and community support. For example, the latest version has features such as transactions and aggregation pipeline optimization. Make sure the version is compatible with the application. For production environments, choose the long-term support version. The latest version has more active community support.

The difference between nodejs and vuejs The difference between nodejs and vuejs Apr 21, 2024 am 04:17 AM

Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

Where is the database created by mongodb? Where is the database created by mongodb? Apr 07, 2024 pm 05:39 PM

The data of the MongoDB database is stored in the specified data directory, which can be located in the local file system, network file system or cloud storage. The specific location is as follows: Local file system: The default path is Linux/macOS:/data/db, Windows: C:\data\db. Network file system: The path depends on the file system. Cloud Storage: The path is determined by the cloud storage provider.

What are the advantages of mongodb database What are the advantages of mongodb database Apr 07, 2024 pm 05:21 PM

The MongoDB database is known for its flexibility, scalability, and high performance. Its advantages include: a document data model that allows data to be stored in a flexible and unstructured way. Horizontal scalability to multiple servers via sharding. Query flexibility, supporting complex queries and aggregation operations. Data replication and fault tolerance ensure data redundancy and high availability. JSON support for easy integration with front-end applications. High performance for fast response even when processing large amounts of data. Open source, customizable and free to use.

What does mongodb mean? What does mongodb mean? Apr 07, 2024 pm 05:57 PM

MongoDB is a document-oriented, distributed database system used to store and manage large amounts of structured and unstructured data. Its core concepts include document storage and distribution, and its main features include dynamic schema, indexing, aggregation, map-reduce and replication. It is widely used in content management systems, e-commerce platforms, social media websites, IoT applications, and mobile application development.

Let's learn how to input the root number in Word together Let's learn how to input the root number in Word together Mar 19, 2024 pm 08:52 PM

When editing text content in Word, you sometimes need to enter formula symbols. Some guys don’t know how to input the root number in Word, so Xiaomian asked me to share with my friends a tutorial on how to input the root number in Word. Hope it helps my friends. First, open the Word software on your computer, then open the file you want to edit, and move the cursor to the location where you need to insert the root sign, refer to the picture example below. 2. Select [Insert], and then select [Formula] in the symbol. As shown in the red circle in the picture below: 3. Then select [Insert New Formula] below. As shown in the red circle in the picture below: 4. Select [Radical Formula], and then select the appropriate root sign. As shown in the red circle in the picture below:

Where are the mongodb database files? Where are the mongodb database files? Apr 07, 2024 pm 05:42 PM

The MongoDB database file is located in the MongoDB data directory, which is /data/db by default, which contains .bson (document data), ns (collection information), journal (write operation records), wiredTiger (data when using the WiredTiger storage engine ) and config (database configuration information) and other files.

How to open mongodb How to open mongodb Apr 07, 2024 pm 06:15 PM

On Linux/macOS: Create the data directory and start the "mongod" service. On Windows: Create the data directory and start the MongoDB service from Service Manager. In Docker: Run the "docker run" command. On other platforms: Please consult the MongoDB documentation. Verification method: Run the "mongo" command to connect and view the server version.

See all articles