发布于 2015-09-14 15:03:18 | 230 次阅读 | 评论: 0 | 来源: 网络整理
The eval command evaluates JavaScript functions on the database server and has the following form:
{
eval: <function>,
args: [ <arg1>, <arg2> ... ],
nolock: <boolean>
}
The command contains the following fields:
Fields: |
|
---|
Consider the following example which uses eval to perform an increment and calculate the average on the server:
db.runCommand( {
eval: function(name, incAmount) {
var doc = db.myCollection.findOne( { name : name } );
doc = doc || { name : name , num : 0 , total : 0 , avg : 0 };
doc.num++;
doc.total += incAmount;
doc.avg = doc.total / doc.num;
db.myCollection.save( doc );
return doc;
},
args: [ "eliot", 5 ]
}
);
The db in the function refers to the current database.
The shell also provides a helper method db.eval(), so you can express the above as follows:
db.eval( function(name, incAmount) {
var doc = db.myCollection.findOne( { name : name } );
doc = doc || { name : name , num : 0 , total : 0 , avg : 0 };
doc.num++;
doc.total += incAmount;
doc.avg = doc.total / doc.num;
db.myCollection.save( doc );
return doc;
},
"eliot", 5 );
The db.eval() method does not support the nolock option.
If you want to use the server’s interpreter, you must run eval. Otherwise, the mongo shell’s JavaScript interpreter evaluates functions entered directly into the shell.
If an error occurs, eval throws an exception. Consider the following invalid function that uses the variable x without declaring it as an argument:
db.runCommand(
{
eval: function() { return x + x; },
args: [3]
}
)
The statement will result in the following exception:
{
"errno" : -3,
"errmsg" : "invoke failed: JS Error: ReferenceError: x is not defined nofile_b:1",
"ok" : 0
}
警告
也可以参考