0

Have the following function created in MongoDB server.

db.system_js.sum = "function (x, y) { return x + y; }" This function sum is saved in current DB's system.js collection

Can execute this function in mongodb shell using step1 : db.loadServerScripts() step2 : sum(2,3) output : 5.

Advice how do I call/execute the sum function from python shell?

  • Try [this](https://stackoverflow.com/questions/29704284/how-do-i-execute-a-mongodb-js-script-using-the-java-mongodriver). – D. SM Apr 18 '20 at 18:33
  • this doesnt work. pymongo.errors.OperationFailure: no such command: 'db.loadServerScripts()' pymongo.errors.OperationFailure: no such command: 'echoFunction(3)' need a simple steps to execute. – Vijaya Bhaskar Apr 19 '20 at 05:49
  • Read the answers carefully. You need to use different syntax when invoking server-side JS from a driver vs the shell. – D. SM Apr 19 '20 at 09:01
  • I understand, however db.eval has been removed and pymongo doesnt support it. only the first part works well, not the second part. More over i see your example is more on the Java code. I am looking something from python shell to execute the saved function on server. Can you try the above code once in python and let me know pls. – Vijaya Bhaskar Apr 19 '20 at 11:23

1 Answers1

0

You cannot in the same way that mongo shell allows it.

Per the documentation:

db.loadServerScripts() loads all scripts in the system.js collection for the current database into the mongo shell session.

Since both mongo shell and the server have a JS interpreter, it is possible to load scripts defined on the server (in the system.js collection) into the mongo shell.

Python interpreter interprets Python, not JS. It is not possible to load JS functions into a Python interpreter directly.

If you wish you can use something like this to run JS from Python.

D. SM
  • 13,584
  • 3
  • 12
  • 21