Write Scripts for the mongo Shell

You can write scripts for the mongo shell in JavaScript thatmanipulate data in MongoDB or perform administrative operation.

This tutorial provides an introduction to writing JavaScript that usesthe mongo shell to access MongoDB.

Opening New Connections

From the mongo shell or from a JavaScript file, you caninstantiate database connections using the Mongo()constructor:

  1. new Mongo()
  2. new Mongo(<host>)
  3. new Mongo(<host:port>)

Consider the following example that instantiates a new connection tothe MongoDB instance running on localhost on the default port and setsthe global db variable to myDatabase using thegetDB() method:

  1. conn = new Mongo();
  2. db = conn.getDB("myDatabase");

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() methodto connect to the MongoDB instance. The following example connects tothe MongoDB instance that is running on localhost with thenon-default port 27020 and set the global db variable:

  1. db = connect("localhost:27020/myDatabase");

See also

mongo Shell Methods

Differences Between Interactive and Scripted mongo

Note

Starting in version 4.2, mongo shell provides themethod isInteractive() that returns a boolean indicatingwhether the mongo shell is running in interactive orscript mode.

When writing scripts for the mongo shell, consider thefollowing:

  • To set the db global variable, use the getDB()method or the connect() method. You can assign the databasereference to a variable other than db.

  • Write operations in the mongo shell use a write concern of{ w: 1 } by default. If performing bulk operations, usethe Bulk() methods. SeeWrite Method Acknowledgements for more information.

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

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

Shell HelpersJavaScript Equivalentsshow dbs, show databases

  1. db.adminCommand('listDatabases')
  1. use <db>
  1. db = db.getSiblingDB('<db>')
  1. show collections
  1. db.getCollectionNames()
  1. show users
  1. db.getUsers()
  1. show roles
  1. db.getRoles({showBuiltinRoles: true})
  1. show log <logname>
  1. db.adminCommand({ 'getLog' : '<logname>' })
  1. show logs
  1. db.adminCommand({ 'getLog' : '*' })
  1. it
  1. cursor = db.collection.find()
  2. if ( cursor.hasNext() ){
  3. cursor.next();
  4. }
  • In interactive mode, mongo prints the results ofoperations including the content of all cursors. In scripts, eitheruse the JavaScript print() function or the mongospecific printjson() function which returns formatted JSON.

Example

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

  1. cursor = db.collection.find();
  2. while ( cursor.hasNext() ) {
  3. printjson( cursor.next() );
  4. }

Scripting

From the system prompt, use mongo to evaluate JavaScript.

—eval option

Use the —eval option to mongo topass the shell a JavaScript fragment, as in the following:

  1. mongo test --eval "printjson(db.getCollectionNames())"

This returns the output of db.getCollectionNames() using themongo shell connected to the mongod ormongos instance running on port 27017 on thelocalhost interface.

Execute a JavaScript file

You can specify a .js file to the mongo shell, andmongo will execute the JavaScript directly. Consider thefollowing example:

  1. mongo localhost:27017/test myjsfile.js

This operation executes the myjsfile.js script in amongo shell that connects to the test databaseon the mongod instance accessible via the localhostinterface on port 27017.

Alternately, you can specify the mongodb connection parameters insideof the javascript file using the Mongo() constructor. SeeOpening New Connections for more information.

You can execute a .js file from within the mongo shell,using the load() function, as in the following:

  1. load("myjstest.js")

This function loads and executes the myjstest.js file.

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

  1. load("scripts/myjstest.js")
  2. load("/data/db/scripts/myjstest.js")

Note

There is no search path for the load()function. If the desired script is not in the current workingdirectory or the full specified path, mongo will not beable to access the file.