发布于 2015-09-14 15:01:04 | 159 次阅读 | 评论: 0 | 来源: 网络整理
The db.eval() provides the ability to run JavaScript code on the MongoDB server. It is a mongo shell wrapper around the eval command. However, unlike the eval command, the db.eval() method does not support the nolock option.
The method accepts the following parameters:
参数: |
|
---|
Consider the following example of the db.eval() method:
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;
},
"<name>", 5 );
If you want to use the server’s interpreter, you must run db.eval(). Otherwise, the mongo shell’s JavaScript interpreter evaluates functions entered directly into the shell.
If an error occurs, db.eval() throws an exception. Consider the following invalid function that uses the variable x without declaring it as an argument:
db.eval( function() { return x + x; }, 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
}
警告
也可以参考