Note: The MongoDB version used by the author is 2.4.7.
Examples of Getting Started
Copy Code code as follows:
conn = new Mongo ();
db = Conn.getdb ("db-name"); //Select Database
Db.auth ("User-name", "password"); //user authentication
var map = f Unction () {
Split_result = This.sentence.split ("");
for (var i in Split_result) {
var word = Split_result[i ].replace (/(^\s*) | ( \s*$)/g, ""). toLowerCase (); Remove possible spaces on both sides of the word and convert the word to lowercase
if (word.length!= 0) {
emit (Word, 1);
}
}
}
var reduce = function (key, values) {
print (key+ ":" +array.sum (values));
return Array.sum (values);
}
Db.data.mapReduce (
map,
Reduce,
{ Out:{merge: "Mr_result"}}
)
Save As Test01.js, run in Terminal:
Copy Code code as follows:
The MapReduce results can be viewed in the collection Mr_result after the run is complete.
It is noteworthy that in the JS script if the direct:
Copy Code code as follows:
is unable to output the result.
You should use the following method to output the results:
Copy Code code as follows:
conn = new Mongo ();
db = Conn.getdb ("Db-name"); Select Database
Db.auth ("User-name", "password"); User authentication
var cursor = Db.mr_result.find ();
while (Cursor.hasnext ()) {
R = Cursor.next ();
Print (r["_id"] + "T" + r["value"]);
}
Save As Test02.js, run:
Copy Code code as follows:
The results are as follows:
Copy Code code as follows:
a 1
code 1
collection 1
consider 1
contains 1
documents 1
error 1
follow 1
following 3
found 1
get & nbsp; 1
i 2
in 1
Link 1
map-reduce 1
of 1
on& nbsp; 1
operations 1
orders 1
Prototype 1
that 1
the 4
this 1
when 1
Using the load () function
The load () function is used to introduce additional files, which facilitates code reuse. The simplest scenario is to put the code for the database connection operation in a separate file, set up lib in the current directory, and create a file Base_operation.js in the Lib directory, which reads as follows:
Copy Code code as follows:
function Baseoperation () {
/*
Connecting to the database, returning the Connection object
*/
This.getdb = function () {
conn = new Mongo ();
db = Conn.getdb ("Db-name");
Db.auth ("User-name", "password");
return DB;
}
}
Create a file test03.js in the current directory, as follows:
Copy Code code as follows:
Load ("Lib/base_operation.js");
BO = new Baseoperation ();
db = Bo.getdb ();
var cursor = Db.mr_result.find ();
while (Cursor.hasnext ()) {
R = Cursor.next ();
Print (r["_id"] + "T" + r["value"]);
}
The effect of running test03.js is the same as test02.js.