MongoDB Map Reduce
Map-Reduce is a computational model. Simply put, it breaks large batches of work (data) into pieces for execution (MAP), and then merges the results into a final result (REDUCE).
The Map-Reduce provided by MongoDB is very flexible and quite practical for large-scale data analysis.
MapReduce command
The following is the basic syntax of MapReduce:
>db.collection.mapReduce(
function() {emit(key,value);}, //map 函数
function(key,values) {return reduceFunction}, //reduce 函数
{
out: collection,
query: document,
sort: document,
limit: number
}
)
Using MapReduce requires implementing two functions, the Map function and the Reduce function. The Map function calls emit(key, value), traverses all records in the collection, and passes the key and value to the Reduce function for processing.
The Map function must call emit(key, value) to return key-value pairs.
Parameter description:
- map : The mapping function (generates a sequence of key-value pairs as arguments to the reduce function).
- reduce The statistics function; the task of the reduce function is to turn key-values into key-value, that is, to turn the values array into a single value.
- out The collection where the statistics result is stored (if not specified, a temporary collection is used, which is automatically deleted after the client disconnects).
- query A filter condition; only documents that satisfy the condition will invoke the map function. (query, limit, and sort can be combined freely)
- sort The sort parameter combined with limit (also sorting documents before sending them to the map function), which can optimize the grouping mechanism
- limit The upper limit on the number of documents sent to the map function (without limit, using sort alone is of little use)
The following example finds data with status:"A" in the orders collection, groups by cust_id, and calculates the total of amount.
Using MapReduce
Consider the following document structure for storing users' articles. The document stores the user's user_name and the article's status field:
>db.posts.insert({
"post_text": "Runoob Tutorial,最全的技术文档。",
"user_name": "mark",
"status":"active"
})
WriteResult({ "nInserted" : 1 })
>db.posts.insert({
"post_text": "Runoob Tutorial,最全的技术文档。",
"user_name": "mark",
"status":"active"
})
WriteResult({ "nInserted" : 1 })
>db.posts.insert({
"post_text": "Runoob Tutorial,最全的技术文档。",
"user_name": "mark",
"status":"active"
})
WriteResult({ "nInserted" : 1 })
>db.posts.insert({
"post_text": "Runoob Tutorial,最全的技术文档。",
"user_name": "mark",
"status":"active"
})
WriteResult({ "nInserted" : 1 })
>db.posts.insert({
"post_text": "Runoob Tutorial,最全的技术文档。",
"user_name": "mark",
"status":"disabled"
})
WriteResult({ "nInserted" : 1 })
>db.posts.insert({
"post_text": "Runoob Tutorial,最全的技术文档。",
"user_name": "runoob",
"status":"disabled"
})
WriteResult({ "nInserted" : 1 })
>db.posts.insert({
"post_text": "Runoob Tutorial,最全的技术文档。",
"user_name": "runoob",
"status":"disabled"
})
WriteResult({ "nInserted" : 1 })
>db.posts.insert({
"post_text": "Runoob Tutorial,最全的技术文档。",
"user_name": "runoob",
"status":"active"
})
WriteResult({ "nInserted" : 1 })
Now, we will use the mapReduce function on the posts collection to select published articles (status:"active"), group by user_name, and count the number of articles per user:
>db.posts.mapReduce(
function() { emit(this.user_name,1); },
function(key, values) {return Array.sum(values)},
{
query:{status:"active"},
out:"post_total"
}
)
The above mapReduce output is:
{
"result" : "post_total",
"timeMillis" : 23,
"counts" : {
"input" : 5,
"emit" : 5,
"reduce" : 1,
"output" : 2
},
"ok" : 1
}
The results show that there are 5 documents matching the query condition (status:"active"), 5 key-value pair documents are generated in the map function, and finally the reduce function groups the same keys into 2 groups.
Specific parameter descriptions:
- result: The name of the collection that stores the results; this is a temporary collection that is automatically deleted after the MapReduce connection is closed.
- timeMillis: The time taken for execution, in milliseconds
- input: The number of documents that satisfy the condition and are sent to the map function
- emit: The number of times emit is called in the map function, that is, the total amount of data in all collections
- output: The number of documents in the result collection ** (count is very helpful for debugging) **
- ok: Whether it succeeded; 1 indicates success
- err: If it fails, the failure reason can be found here, but from experience the reason is rather vague and of little use
Use the find operator to view the query results of mapReduce:
> var map=function() { emit(this.user_name,1); }
> var reduce=function(key, values) {return Array.sum(values)}
> var options={query:{status:"active"},out:"post_total"}
> db.posts.mapReduce(map,reduce,options)
{ "result" : "post_total", "ok" : 1 }
> db.post_total.find();
The above query displays the following result:
{ "_id" : "mark", "value" : 4 }
{ "_id" : "runoob", "value" : 1 }
In a similar way, MapReduce can be used to build large and complex aggregation queries.
The Map function and Reduce function can be implemented in JavaScript, making the use of MapReduce very flexible and powerful.