Write Scripts for the MongoDB Shell¶
On this page
You can write scripts for the MongoDB Shell that manipulate data in MongoDB or perform administrative operations.
Open a New Connection¶
database connections using the
new Mongo() new Mongo(<host>) new Mongo(<host:port>)
Consider a MongoDB instance running on localhost on the default port.
The following example:
- Instantiates a new connection to the instance, and
- Sets the global
conn = Mongo(); db = conn.getDB("myDatabase");
If you connect to a MongoDB instance that enforces access control, you must include the credentials in the connection string.
The following command connects to a MongoDB instance that is:
- Running on
localhoston the default port, and
- Secured using SCRAM.
conn = Mongo("mongodb://<username>:<password>@localhost:27017/<authDB>");
Additionally, you can use the connect() method to connect to the MongoDB instance.
The following command:
- Connects to the MongoDB instance that is running on
localhostwith the non-default port
- Sets the global
db = connect("localhost:27020/myDatabase");
require() to Include External Files and Modules¶
You can use the require() function in the MongoDB Shell to include modules which exist in separate files.
Require a File¶
additional setup or configuration.
The MongoDB Shell does not execute files imported with
The MongoDB Shell adds everything from an imported file to the current
Use one of the following commands include a file from the current
working directory named
var tests = require('./tests.js')
Require a Native Module¶
require() native Node modules (such as
fs) in the
MongoDB Shell without any additional setup or configuration.
Use one of the following commands to include the
var fs = require('fs');
Require a Non-Native Module¶
require() non-native Node modules (such as those downloaded from
npm) you must install the module globally
or to the
node_modules directory in your current working directory.
Once you install or copy your desired package to one of the module
directories, you can
require() that package.
Use one of the following commands to include the moment:
var moment = require('moment')
You can execute a
.js file from within the MongoDB Shell
The following command loads and executes the
.load command accepts relative and absolute paths. If the
current working directory of the MongoDB Shell is
myjstest.js resides in the
/data/db/scripts directory, then
the following calls within the MongoDB Shell are equivalent:
.load scripts/myjstest.js .load /data/db/scripts/myjstest.js
There is no search path for the
.load command. If the desired
script is not in the current working directory or the full specified
path, the MongoDB Shell cannot access the file.