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()
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()
The simplest way I found of running mongodb queries from a file and seeing the output in the console is this:
query.js
: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.
Put this into your
query.js
file:and run:
Here's a good explanation why you should do it this way.
One thing other answers didn't mention is that
use db
command won't work in external script. The best way is to usegetSiblingDB
, for example, if I want to use database calledmy_db
:Then everything works as you would expect. See Write Scripts for the mongo Shell.
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)
Command
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: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 requirestest.js
to be proper javascript and cannot use the mongo shell convenience methods likeuse test
; one would use the javascript equivalents likegetSiblingDB()
.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)
Then replace
192.168.1.1
with the ip / hostname of your db,YourDataBase
with the database name and point to an existing file