How to run a local script in mongo shell - Solution load()

Steve Taylor picture Steve Taylor · Jun 30, 2017 · Viewed 9.5k times · Source

I think this is a very basic question but I'm stuck. I'm connected to remote mongo instance (mLab) via a MongoDB shell. This has been fine for one-liners, but now I want to run larger commands but often, thus the need to do it from an already connected shell.

How can I run my local script.js from the mongo shell and get the output in the shell, as if I'm just running the one-liner per usual?

I was hoping load("script.js") would do it, but it just returns 'true' regardless of the content.

Answer

karthik006 picture karthik006 · Jun 30, 2017

Execute a JavaScript file

You can specify a .js file to the mongo shell, and mongo will execute the JavaScript directly. Consider the following example:

mongo localhost:27017/test myjsfile.js

Replace the Localhost URL with your Mlab URL

Or if you are in the shell You can execute a .js file from within the mongo shell, using the load() function, as in the following:

load("myjstest.js")

refer to this link

Modify your script file to print all items in a result cursor , use the following idiom:

cursor = db.collection.find();
 while ( cursor.hasNext() ) {
   printjson( cursor.next() );
}