Write Scripts for the mongo Shell
You can write scripts for the
mongo shell to access MongoDB.
Consider the following example that instantiates a new connection to the MongoDB instance running on localhost on the default port and sets the global
db variable to
myDatabase using the
If connecting to a MongoDB instance that enforces access control, you can use the
db.auth() method to authenticate.
Additionally, you can use the
connect() method to connect to the MongoDB instance. The following example connects to the MongoDB instance that is running on
localhost with the non-default port
27020 and set the global
When writing scripts for the
mongo shell, consider the following:
To set the
dbglobal variable, use the
getDB()method or the
connect()method. You can assign the database reference to a variable other than
You cannot use any shell helper (e.g.
The following table maps the most common
In interactive mode,
print()function or the
printjson()function which returns formatted JSON.
To print all items in a result cursor in
mongoshell scripts, use the following idiom:
From the system prompt, use
Mongo() constructor. See Opening New Connections for more information.
You can execute a
.js file from within the
mongo shell, using the
load() function, as in the following:
This function loads and executes the