Functions Implementation and Understanding

I am trying to create function in MongoDB and then call it. I am unable to do so.
I tried 2 ways

  1. db.Test.save({
    _id: “displayMessage”,
    value: function (data) {
    return 'The Name is: ’ + data;
    }
    })

This method, I call like

db.eval(“displayMessage(‘John’)”);
but no success. I come to know that eval is not supported anymore. I would Like to know that how to call it now!

  1. I created this function in ROBO3T
    image

When I pass value, this happens.
image

I want to understand how to understand and Implement functions in MongoDB. Can’t find any implementation or understanding so far.

Hi @MWD_Wajih_N_A,

See the documentation for Store a JavaScript Function on the Server to see how a function can be stored.

To use these functions in the mongo shell they will have to be loaded via a call to db.loadServerScripts() first.

For example:

db.system.js.insertOne(
   {
     _id: "echoFunction",
     value : function(x) { return x; }
   }
);
db.loadServerScripts();
echoFunction("test")

Note that these server-side JavaScript functions are not the same thing as MongoDB Realm Functions.

1 Like

Hi @alexbevi,

I am getting db.loadServerScripts() is not a function from mongoshell while running from mongoshell and atlas’s shell, how can i solve this issue ?
Mongoshell version: 1.1.7
Mongo atlas version: 1.28.4

Appreciate any help.

Hello.

I’m having exactly the same issue when using MongoDB Shell, this is not a problem if I use the “Legacy” shell from Mongo 4.2; I suspect the problem is that db.loadServerScripts() is not yet supported on MongoDB Shell or at least that method is not listed at https://www.mongodb.com/docs/mongodb-shell/reference/methods/ yet.

Does anyone know if there a workaround for this other than loading the custom functions from a JS file?

1 Like