Introduction and introductory examples of javascript scripting in MongoDB

  • 2020-05-10 23:06:39
  • OfStack

Note: the mongodb version used by the author is 2.4.7.

Introductory example


conn = new Mongo();
db = conn.getDB("db-name");  // Select database 
db.auth("user-name","password");  // User authentication 
var map = function() {
    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 either side 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 and run in the terminal:

$ mongo test01.js

You can view the mapreduce results in the collection mr_result after the run.

It is worth noting that in the js script if you directly:

db.mr_result.find();

You can't output the result.

You should output the results in the following manner:

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:
$ mongo test02.js

The results are as follows:

a       1
code    1
collection      1
consider        1
contains        1
documents       1
error   1
follow  1
following       3
found   1
get     1
i       2
in      1
link    1
map-reduce      1
of      1
on      1
operations      1
orders  1
prototype       1
that    1
the     4
this    1
when    1

Use the load() function

The load() function is used to introduce other files, which facilitates code reuse. In the simplest case, put the code for the database connection operation in a separate file, create lib in the current directory, and base_operation.js in the lib directory, as follows:


function BaseOperation() {
    /*
     Connect to the database and return 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, which reads 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"]);
}

Running test03.js has the same effect as running test02.js.


Related articles: