在mongodb中调用存储的函数

时间:2013-08-12 10:54:23

标签: mongodb mongodb-java

我在mongdb中调用存储函数时遇到了一些困难。 我和mongo有点新手。

[编辑]:我的函数存储在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调用此函数。

5 个答案:

答案 0 :(得分:13)

考虑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

答案 1 :(得分:7)

在mongo shell中,您可以使用db.loadServerScripts()来加载当前数据库的system.js集合中保存的所有脚本。加载后,您可以直接在shell中调用函数,如下例

db.loadServerScripts();

mySampleFunction(3, 5);

答案 2 :(得分: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 字段包含函数的名称,并且每个数据库都是唯一的。

字段包含函数定义。

mongo shell中,您可以使用

  

db.loadServerScripts()

加载当前数据库的system.js集合中保存的所有脚本。加载后,您可以直接在shell中调用函数,如下例所示:

db.loadServerScripts();

echoFunction(3);

myAddFunction(3, 5);

来源:MONGODB MANUAL

答案 3 :(得分:2)

您可以像这样调用您的函数

db.loadServerScripts();
db.data.insert({
   _id: myFunction(5),
    name: "TestStudent"
});

如果我的函数使用命令存储在db中:

db.system.js.save(
 {
  _id : "myFunction" ,
  value : function (x){ return x + 1; }
  });

答案 4 :(得分:0)

我认为你需要使用$ 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/