mongo shell does not output result of command when executing a javascript file

2,764 views
Skip to first unread message

Martin Lichtin

unread,
Jun 18, 2015, 10:48:13 AM6/18/15
to mongod...@googlegroups.com
For some reason, the mongo shell does not output the result of the command when a Javascript file is executed:

$ echo "db.stats()" >db-stats.js
$ mongo -u user -p pass db db-stats.js
MongoDB shell version: 3.0.3
connecting to: db
$

There's no output or any indication of how it went, as far as I can see.
Is there a way to improve this?

For example, when I run mongo shell semi-interactively, then I see the result:

$ echo "db.stats()" |  mongo -u user -p pass db
MongoDB shell version: 3.0.3
connecting to: db
{
        "ok" : 0,
        "errmsg" : "not authorized on db to execute command { dbstats: 1.0, scale: undefined }",
        "code" : 13
}
bye

acveer

unread,
Jun 18, 2015, 11:38:34 AM6/18/15
to mongod...@googlegroups.com
It looks like it does print fine as I see the ok:1 and err message.
Also add 'use $databaseName;' to the .js file before calling db.stats().

show dbs; //showdbs.js file

$mongo < showdbs.js

MongoDB shell version: 3.0.4
connecting to: test
Northwind      0.078GB
bye

Martin Lichtin

unread,
Jun 22, 2015, 3:34:47 AM6/22/15
to mongod...@googlegroups.com
Yes, but don't use it the same way. It works when providing the Javascript as stdin.
But when providing the Javascript file as an argument to mongo, then it doesn't.
In your case, try

mongo showdbs.js

and I bet you don't see the expected output.

Stephen Steneker

unread,
Jun 22, 2015, 3:45:28 AM6/22/15
to mongod...@googlegroups.com, mlic...@gmail.com
On Monday, 22 June 2015 17:34:47 UTC+10, Martin Lichtin wrote:
Yes, but don't use it the same way. It works when providing the Javascript as stdin.
But when providing the Javascript file as an argument to mongo, then it doesn't.

Hi Martin,

There are some differences in running a script via the command line vs the interactive mode of the mongo shell:
 http://docs.mongodb.org/manual/tutorial/write-scripts-for-the-mongo-shell/#differences-between-interactive-and-scripted-mongo

In particular, the interactive shell automatically prints the results of operations whereas you need to intentionally request this for a command line script.

If you wrap your command in the JS file with explicit printjson() or print(), you should see the output.

For example, db-stats.js would contain:
  printjson(db.stats())

Regards,
Stephen

Martin Lichtin

unread,
Jun 22, 2015, 2:18:24 PM6/22/15
to mongod...@googlegroups.com, mlic...@gmail.com
That's it, thanks!
Reply all
Reply to author
Forward
0 new messages