After running the command mongo --help
, we found the following information:
$ mongo --help
MongoDB shell version v3.6.2
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
foo foo database on local machine
192.168.0.5/foo foo database on 192.168.0.5 machine
192.168.0.5:9999/foo foo database on 192.168.0.5 machine on port 9999
Options:
--shell run the shell after executing files
--nodb don't connect to mongod on startup - no
'db address' arg expected
--norc will not run the ".mongorc.js" file on
start up
--quiet be less chatty
--port arg port to connect to
--host arg server to connect to
--eval arg evaluate javascript
-h [ --help ] show this usage information
... ...
Furthermore, upon consulting MongoDB's documentation, we came across a script named my-mongo-script.js
:
'use strict';
// @see https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/
var MONGODB_URI = "mongodb://127.0.0.1:27020/testdb";
var db = connect(MONGODB_URI);
var collections = db.getCollectionNames();
print(collections.join('\n'));
printjson(collections);
Executing the command mongo --nodb my-mongo-script.js
will run this script. To include the "--shell" option and run the shell after executing files, you can use
mongo --nodb --shell my-mongo-script.js
.