MongoDB Scripting

MongoDB Scripting

The mongo shell is an interactive JavaScript shell for MongoDB, and is part of all MongoDB distributions. This section provides an introduction to the shell, and outlines key functions, operations, and use of the mongo shell.

Server-side JavaScript – Changed in version 2.4: The V8 JavaScript engine, which became the default in 2.4, allows multiple JavaScript operations to execute at the same time. Prior to 2.4, MongoDB operations that required the JavaScript interpreter had to acquire a lock, and a single mongod could only run a single JavaScript operation at a time. MongoDB supports the execution of JavaScript code for the following server-side operations:

  • mapReduce and the corresponding mongo shell method db.collection.mapReduce().
  • eval command, and the corresponding mongo shell method db.eval()
  • $where operator
  • Running .js files via a mongo shell Instance on the Server

Although the above operations use JavaScript, most interactions with MongoDB do not use JavaScript but use an idiomatic driver in the language of the interacting application.

You can disable all server-side execution of JavaScript, by passing the –noscripting option on the command line or setting noscripting in a configuration file.

Running .js files via a mongo shell Instance on the Server – You can run a JavaScript (.js) file using a mongo shell instance on the server. This is a good technique for performing batch administrative work. When you run mongo shell on the server, connecting via the localhost interface, the connection is fast with low latency.

The command helpers provided in the mongo shell are not available in JavaScript files because they are not valid JavaScript. The following table maps the most common mongo shell helpers to their JavaScript equivalents.

Shell HelpersJavaScript Equivalents
show dbs, show databasesdb.adminCommand(‘listDatabases’)
use <db>db = db.getSiblingDB(‘<db>’)
show collectionsdb.getCollectionNames()
show usersdb.getUsers()
show rolesdb.getRoles({showBuiltinRoles: true})
show log <logname>db.adminCommand({ ‘getLog’ : ‘<logname>’ })
show logsdb.adminCommand({ ‘getLog’ : ‘*’ })
itcursor = db.collection.find()   if ( cursor.hasNext() ){ cursor.next(); }

Write Scripts for the mongo Shell – You can write scripts for the mongo shell in JavaScript that manipulate data in MongoDB or perform administrative operation.

Opening New Connections – From the mongo shell or from a JavaScript file, you can instantiate database connections using the Mongo() constructor:

new Mongo()

new Mongo(<host>)

new Mongo(<host:port>)

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:

conn = new Mongo();

db = conn.getDB(“myDatabase”);

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:

db = connect(“localhost:27020/myDatabase”);

Differences Between Interactive and Scripted mongo – When writing scripts for the mongo shell, consider the following:

  • To set the db global variable, use the getDB() method or the connect() method. You can assign the database reference to a variable other than db.
  • Inside the script, call db.getLastError() explicitly to wait for the result of write operations.
  • You cannot use any shell helper (e.g. use <dbname>, show dbs, etc.) inside the JavaScript file because they are not valid JavaScript.

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. As an example, to print all items in a result cursor in mongo shell scripts, use the following idiom:

cursor = db.collection.find();

while ( cursor.hasNext() ) {

printjson( cursor.next() );

}

Scripting – From the system prompt, use mongo to evaluate JavaScript.

–eval option – Use the –eval option to mongo to pass the shell a JavaScript fragment, as in the following:

mongo test –eval “printjson(db.getCollectionNames())”

This returns the output of db.getCollectionNames() using the mongo shell connected to the mongod or mongos instance running on port 27017 on the localhost interface.

Execute a JavaScript file – You can specify a .js file to the mongo shell, and mongo will execute the JavaScript directly. Consider the following example:

mongo localhost:27017/test myjsfile.js

This operation executes the myjsfile.js script in a mongo shell that connects to the test database on the mongod instance accessible via the localhost interface on port 27017. Alternately, you can specify the mongodb connection parameters inside of the javascript file using the Mongo() constructor. You can execute a .js file from within the mongo shell, using the load() function, as in the following:

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

load(“scripts/myjstest.js”)

load(“/data/db/scripts/myjstest.js”)

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

Apply for MongoDB Certification Now!!

https://www.vskills.in/certification/databases/mongodb-server-administrator

Back to Tutorial

Recover Data after an Unexpected Shutdown
Security Introduction

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?