Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 884
Steve Taylor Avatar asked Jun 30 '17 05:06

Steve Taylor


1 Answers

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() );
}
like image 192
karthik006 Avatar answered Nov 07 '22 15:11

karthik006