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

This question already has answers here:
How to execute mongo commands through shell scripts?
(22 answers)
Closed 5 years ago.
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.

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() );
}

Related

How to save larger files using Mongo CLI

I am trying to use the mongo CLI to save a larger-than-usual JSON (using db.mycollection.save(...)) but the mongo command line doesn't accept the full length of the JSON (I believe the length limit accepted by the command line is 4096, which is shorter than my JSON).
Is there another way to save this JSON to Mongo, using native functionality from the mongo CLI? (I am trying to do this by invoking mongo commands from a bash script)
Thanks!
If anyone else has this difficulty, I solved it by calling
eval "mongo myJsFile.js"
instead of
mongo < myJsFile.js
in the bash script

MongoDB remote shell script create database

New to this forum, to mongodb , My goal is to automate a database creation from a linux BATCH on a computer client to the server.
conn = new mongo(); "returns OK"
db = conn.getDB("admin"); "returns OK"
db.runCommand( { use NewDatabase } ) "returns *NOK* , this is not the good syntax "
Can't found the way in the Shell Helper , or perhaps i missed it in mongodb help: http://docs.mongodb.org/manual/tutorial/write-scripts-for-the-mongo-shell/
Is there is a solution or do i have to use Py -Pymongo or an another language?
Thank you, sorry for the first post i was not a really nice post.
If you want to create/use a database from a command line passed to the mongo shell you can either:
use the scripted equivalent of use NewDatabase in your JavaScript file:
db = db.getSiblingDB('NewDatabase');
pass the database name your script should execute against on the mongo shell command line:
mongo NewDatabase foo.js
If you don't specify a database name, test is the default name used by the mongo shell.

pretty print in mongo shell not working - MongoDB 2.6 + Yosemite + ZSH [duplicate]

This question already has an answer here:
How do I get colorized query output and shell in MongoDB?
(1 answer)
Closed 8 years ago.
I'm running the mongo shell by invoking mongo at the command line. The result is a bland shell experience. I would like to see colored JSON output, etc. I tried running:
> db.my_collection.find().pretty()
but it didn't work.
I also tried adding the following line to ~/.mongorc.js:
DBQuery.prototype._prettyShell=true
but it didn't work.
Try the MongoDB shell enhancement. You can make particular tweaks after you clone the repo.

Mongo shell execute query from file and show result

How to execute external file using mongo shell and see the result in console?
I have external file, like query.js and I would like to execute it and see the result in cmd.
Let's say, content of the file is:
db.users.find()
Put this into your query.js file:
function get_results (result) {
print(tojson(result));
}
db.col.find().forEach(get_results)
and run:
mongo db_name query.js
Here's a good explanation why you should do it this way.
The simplest way I found of running mongodb queries from a file and seeing the output in the console is this:
query.js:
use my_db;
db.my_collection.findOne()
On the command line:
mongo <query.js
This displays all the output to the console, as if you were running the queries in the mongo shell individually.
Good information here - wanted to point out that mongo provides a printjson() function so there is no need to write your own unless you need more functionality than printjson() provides.
Example Mongo file (test.js)
// Pretty print all documents in test.scratch
use test
db.scratch.find().forEach(printjson)
Command
mongo < test.js
If you want to omit use test from the mongo file, perhaps to remove IDE error indications for js files, you can specify the target db on the command line:
mongo test < test.js
Interesting to note: the above examples use a redirect to push the file into the mongo shell. This calling convention allows you to enter commands just as you would in the shell; including mongo shell convenience commands like use test.
Mongo provides another script calling convention: mongo test test.js which omits the redirect operator. This calling convention requires test.js to be proper javascript and cannot use the mongo shell convenience methods like use test; one would use the javascript equivalents like getSiblingDB().
One thing other answers didn't mention is that use db command won't work in external script. The best way is to use getSiblingDB, for example, if I want to use database called my_db:
db = db.getSiblingDB("my_db");
function get_results (result) {
print(tojson(result));
}
db.col.find().forEach(get_results)
Then everything works as you would expect. See Write Scripts for the mongo Shell.
This seems to have changed at some point in the mongo cli, I had to execute the following command to get it to run a file against the database (with mongo cli version 3.4.9)
mongo mongodb://192.168.1.1/YourDataBase scriptFile.js
Then replace 192.168.1.1 with the ip / hostname of your db, YourDataBase with the database name and point to an existing file

mongo shell / simple example for windows XP

New to Mongo, just experimenting w the shell on a Windows XP machine running Mongo 2.0.1.
At the ">" mongo.exe cmd prompt, what do I enter in order to read cmds from another file called TEST.js ? I put a TEST.js file every place I could think of, and typed things like ">./mongo TEST.js", ">.mongo full-pathname.js", ">TEST.js", etc.
Is there a way to do this ?
(Why?: I loaded a bunch of data w mongoimport & thought I could try a quick-and-dirty mapreduce from the > shell prompt prior to setting up via a ruby or python driver & doing it the right way. The map,reduce & finalize funcs are sitting in a *.js file, and I need those function defs imported before I can run the mapreduce method on my data collection.)
From the Windows XP command prompt, you can run the mongo shell (mongo.exe in Windows) with the "--shell" option followed by your filespec to start the mongo shell, load your file and then remain in the mongo shell. If your file defines "map" and "reduce" functions, those will be available to you at the mongo shell's prompt.
For example, "mongo --shell TEST.js" .
Alternatively, you can start the mongo shell and then issue a "load" command to load your JavaScript file. The command 'load("TEST.js")' should do it for you.
If these are functions you will want every time you start the mongo shell, you can put the JavaScript into a file named ".mongorc.js" (note the initial period) in your "user" directory, for example "C:\Documents and Settings\YourName\.mongorc.js" on Windows XP when logged in as YourName. The .mongorc.js feature was introduced in version 1.9, so your version has it.