When writing scripts for the mongo shell, we cannot use the shell helpers. MongoDB's commands, such as use <database_name>, show collections, and other helpers are built into the shell and so are not available from the JavaScript context where our scripts will get executed. Fortunately, there are equivalents to them that are available from the JavaScript execution context, as shown in the following table:
Shell helpers |
JavaScript equivalents |
show dbs, show databases |
db.adminCommand('listDatabases') |
use <database_name> |
db = db.getSiblingDB('<database_name>') |
show collections |
db.getCollectionNames() |
show users |
db.getUsers() |
show roles |
db.getRoles({showBuiltinRoles: true}) |
show log <logname> |
db.adminCommand({ 'getLog' : '<logname>' }) |
show logs |
db.adminCommand({ 'getLog' : '*' }) |
it |
cursor = db.collection.find() |
In the previous table, it is the iteration cursor that the mongo shell returns when we query and get back too many results to show in one batch.
Using the mongo shell, we can script almost anything that we would from a client, meaning that we have a really powerful tool for prototyping and getting quick insights into our data.