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
getDB() method:

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 db variable:

You cannot use any shell helper (e.g. use<dbname>, showdbs, etc.) inside the JavaScript file because they are not valid
JavaScript.

The following table maps the most common mongo shell
helpers to their JavaScript equivalents.

Shell Helpers

JavaScript Equivalents

showdbs, showdatabases

db.adminCommand('listDatabases')

use<db>

db=db.getSiblingDB('<db>')

showcollections

db.getCollectionNames()

showusers

db.getUsers()

showroles

db.getRoles({showBuiltinRoles:true})

showlog<logname>

db.adminCommand({'getLog':'<logname>'})

showlogs

db.adminCommand({'getLog':'*'})

it

cursor=db.collection.find()if(cursor.hasNext()){cursor.next();}

In interactive mode, mongo prints the results of
operations including the content of all cursors. In scripts, either
use the JavaScript print() function or the mongo
specific printjson() function which returns formatted JSON.

Example

To print all items in a result cursor in mongo shell
scripts, use the following idiom:

The load() method accepts relative and absolute paths.
If the current working directory of the mongo shell
is /data/db, and the myjstest.js resides in the
/data/db/scripts directory, then the following calls within
the mongo shell would be equivalent: