在mongdb中调用存储函数时遇到了一些困难。我对mongo有点陌生。
[EDIT]:我的函数存储在mongodb 中
function() {
var cndTime = new Date().getTime() - (3600*1000*24*2); // condition
db.urls.find(needParse: false).forEach(function(item){
if(item.date < cndTime) // check
db.urls.update({_id: item._id}, {$set: { needParse: true }}); // update field
});
}
我所问的只是如何使用reactivemongo或本机API调用此函数。
考虑mongo shell中的以下示例,该示例首先将名为echoFunction
的函数保存到system.js
集合,并使用db.eval()
调用该函数:
db.system.js.save({
_id: "echoFunction",
value: function (x) {
return 'echo: ' + x;
}
})
db.eval("echoFunction('test')") // -> "echo: test"
echoFunction(...)
在eval
/$where
/mapReduce
等中可用。更多信息请访问http://docs.mongodb.org/manual/tutorial/store-javascript-function-on-server
在mongo shell中,可以使用db.loadServerScripts()加载保存在system.js集合中的当前数据库的所有脚本。加载后,您可以直接在shell中调用函数,如下面的示例所示
db.loadServerScripts();
mySampleFunction(3, 5);
有一个名为的特殊系统集合
system.js
可以存储JavaScript函数以供重用。
要存储函数,可以使用
db.collection.save()
,如以下示例所示:
db.system.js.save(
{
_id: "echoFunction",
value : function(x) { return x; }
}
);
db.system.js.save(
{
_id : "myAddFunction" ,
value : function (x, y){ return x + y; }
}
);
_id字段包含函数的名称,并且每个数据库都是唯一的。
值字段包含函数定义。
在mongoshell中,您可以使用
db.loadServerScripts()
以加载当前数据库的CCD_ 8集合中保存的所有脚本。加载后,您可以直接在shell中调用函数,如下例所示:
db.loadServerScripts();
echoFunction(3);
myAddFunction(3, 5);
来源:MONGODB MANUAL
您可以像这样调用函数
db.loadServerScripts();
db.data.insert({
_id: myFunction(5),
name: "TestStudent"
});
如果我的函数使用命令存储在数据库中
db.system.js.save(
{
_id : "myFunction" ,
value : function (x){ return x + 1; }
});
我认为您需要使用$where才能使其工作!像这样的东西:
db.urls.find( { needParse: false, $where: function(item){
if(item.date < cndTime) // check
db.urls.update({_id: item._id}, {$set: { needParse: true }});
欲了解更多信息,请阅读:https://docs.mongodb.com/manual/reference/operator/query/where/