Mongo shell execute query from file and show result
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.scratchuse testdb.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()
.