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?

4
  • Try this. Commented Apr 18, 2020 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. Commented Apr 19, 2020 at 5:49
  • Read the answers carefully. You need to use different syntax when invoking server-side JS from a driver vs the shell. Commented Apr 19, 2020 at 9: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. Commented Apr 19, 2020 at 11:23

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.