MongoDB eval Execute server-side script _mongodb

Source: Internet
Author: User
Tags eval mongodb mongodb server

JavaScript scripts can be executed by the Db.eval function on the server side, and JavaScript scripts can be saved in the database and then invoked in other database commands.

One, Db.eval execute server-side script

The Db.eval function enables JavaScript scripts to be executed on the MongoDB server side. This function first passes the given JavaScript string to the MongoDB server, executes on the server, and returns the result.
Db.eval can be used to simulate multiple-document transactions: Db.eval locks the database, then executes JavaScript, and then unlocks it. Although there is no built-in rollback mechanism, this ensures that a sequence of operations occurs according to a specified number of sequences.
There are two ways to send code, either encapsulating a function or not encapsulating it, such as:

Copy Code code as follows:

Db.eval ("return ' refactor ';")
Db.eval ("function () {return ' refactor ';}")

It must be encapsulated into a function only when passing parameters. The parameter is passed through the second argument of the Db.eval, to be written in an array form.
Such as:

Copy Code code as follows:

Db.eval ("function (name) {return ' Hello, ' +name;}", [' Refactor '])

If the db.eval expression is complex, the way to debug is to write debug information into the database log
Such as:

Copy Code code as follows:

Db.eval ("Print (' Hello Refactor ')")

So you can find Hello refactor in the log.

Second, storage JavaScript

Each MongoDB database has a special collection: System.js, which is used to store JavaScript variables. These variables can be invoked in any MongoDB JavaScript context, including the "$where" clause, db.eval invocation, MapReduce the job. With inserts you can place variables in system.js
Such as:

Copy Code code as follows:

Db.system.js.insert ({"_id": "X", "Value": 1})
Db.system.js.insert ({"_id": "Y", "Value": 2})
Db.system.js.insert ({"_id": "Z", "Value": 3})

The example above defines the x,y,z in the global scope and sums it up:

Db.eval ("return x+y+z;")

System.js can store JavaScript code, which makes it easy to customize scripts such as writing a log function in JavaScript and storing it in System.js:

Copy Code code as follows:

Db.system.js.insert (
{
"_id": "Log",
' Value ': function (msg,level)
{
var levels=["DEBUG", "WARN", "ERROR", "Patal"];
level=level?level:0;
var now= new Date ();
Print (now + "" + levels[level]+msg);
}
}
)

Call:

Copy Code code as follows:

Db.eval ("Log (' Refactor Bolg test ', 1)")

The JavaScript disadvantage of using storage is that the code is detached from regular source control and can mess up JavaScript sent by the client.
The best way to use stored JavaScript is to use a JavaScript function somewhere in the program, so if you update it, just update the function without having to modify it. If the JavaScript code is long and cumbersome to use, You can also use storage JavaScript, which saves a lot of transmission time.

Third, security

The execution of JavaScript code takes into account MongoDB security.
Such as:

Copy Code code as follows:

>func= "function () {print (' Hello, +username+ '! ');}"

If username is user-defined, you can use such a string "'";d b.dropdatabase ();p rint (),
The code becomes like this:

Copy Code code as follows:

>func= "function () {print (' Hello, ');d b.dropdatabase ();p rint ('! ');}"

To avoid this situation, qualify the scope.
Most drivers provide a special type of code that is passed to the database because the code can actually be viewed as a combination of a string and a scope. A scope is a document that holds variable name and value mapping relationships. When the JavaScript function executes, This mapping forms the local scope of the function.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.