6

我在 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 调用这个函数。

4

5 回答 5

16

考虑以下来自 mongo shell 的示例,该示例首先将一个名为的函数保存echoFunctionsystem.js集合中并使用 调用该函数db.eval()

db.system.js.save({
    _id: "echoFunction",
    value: function (x) {
        return 'echo: ' + x;
    }
})

db.eval("echoFunction('test')") // -> "echo: test"

echoFunction(...)可在eval//等中找到更多信息,请$where访问http://docs.mongodb.org/manual/tutorial/store-javascript-function-on-servermapReduce

于 2013-08-12T11:08:37.353 回答
12

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

db.loadServerScripts();

mySampleFunction(3, 5);
于 2016-03-08T09:21:18.080 回答
7

有一个特殊的系统集合名为

系统.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字段包含函数的名称,并且每个数据库都是唯一的。

value字段保存函数定义。

mongo shell 中,您可以使用

db.loadServerScripts()

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

db.loadServerScripts();

echoFunction(3);

myAddFunction(3, 5);

资料来源:MONGODB 手册

于 2017-04-12T09:16:30.520 回答
3

你可以这样调用你的函数

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

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

db.system.js.save(
 {
  _id : "myFunction" ,
  value : function (x){ return x + 1; }
  });
于 2017-06-20T06:13:22.927 回答
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/

于 2017-09-05T10:00:19.773 回答