6

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.

Steve Taylor
  • 412
  • 1
  • 4
  • 11
  • Basically `mongo < scriptname.js`. The rest is discussed ( at length ) in the duplicate. – Neil Lunn Jun 30 '17 at 05:09
  • Yes, I understand how to run from the system shell. The point of difference that I'm seeking to run from the mongo shell which is logged into a remote instance. – Steve Taylor Jun 30 '17 at 06:14
  • The solution cited works fine for the problem posed in the dupe, but doesn't solve my problem. Appreciate your efforts @NeilLunn – Steve Taylor Jun 30 '17 at 06:37

1 Answers1

14

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() );
}
James Brown
  • 36,089
  • 7
  • 43
  • 59
karthik006
  • 886
  • 9
  • 19