mongo, the MongoDB Shell

< View all blog posts

July 17, 2012
Category: Release Notes

The MongoDB shell (mongo) is an extended SpiderMonkey (JavaScript) shell, so you can use it to execute JavaScript code just like you’re used to writing.

The shell is best at things like testing out queries, examining specific records, configuring replica sets and sharding, and administrative tasks like creating indexes.

Many objects in the shell have help functions in case you forget how to do things. When in doubt:

    > help
    DB methods:
        db.addUser(username, password[, readOnly=false])
        db.auth(username, password)

    DBCollection help
        db.demo.find().help() - show DBCursor help

Some of the most common tasks the shell is needed for involve sending commands to the MongoDB server - like changing profiler settings, losetting. These kinds of functions are performed by using the shell to send database commands for example db.runCommand("shutdown") or db.runCommand({profile:-1}). You can get info on these commands and how to use them from the shell like this:

    > db.listCommands() // print a listing of all the available commands
    > db.commandHelp("compact") // show details about how to use the "compact" database command.

Sometimes, it’s useful to see how a particular shell function works - you can do this by leaving off the ( ), which forces the shell to print the source code of the function instead of just executing it. For example:

    > db.printReplicationInfo() // print info about current replication status
    > db.printReplicationInfo // print the source code of the printReplicationInfo function
    function () {

In the shell, the default behavior when executing a query is to print the output, unformatted.

    { "_id" : ObjectId("4e697832c67f0623d40000ad"), "content" : "lorem ipsum" }
    . . .
    { "_id" : ObjectId("4e697832c67f0623d40000f0"), "content" : "four score and 7 years ago" }
    has more

Try adding .pretty() to the function to format the output in a more readable matter, like this:


By default, queries with lots of results only print a limit of 20 results at a time - type it at the shell to show the next batch of 20. You can adjust this size limit by setting the value of DBQuery.shellBatchSize.

When the mongo shell starts, it will read and execute any JavaScript code in the file .mongorc.jsin your home directory. By adding your settings, utility functions, or tweaks into this file you can make them available in every shell session. For example, add this snippet of code to the file, and it will allow you to run the inspect() function on any javascript object in the shell, which will print information about its properties:

function inspect(o, i) {
    if (typeof i == "undefined") {
        i = "";
    if (i.length > 50) {
        return "[MAX ITERATIONS]";
    var r = [];
    for (var p in o) {
        var t = typeof o[p];
        r.push(i + "\"" + p + "\" (" + t + ") => " + (t == "object" ? "object:" + xinspect(o[p], i + "  ") : o[p] + ""));
    return r.join(i + "\n");

You can also add snippets of code in your .mongorc.js file to do other cool stuff, like customize your shell prompt. In addition, you can execute any file containing JavaScript code from within the shell by calling load(filename).

Frequently it’s useful to execute some mongo shell commands without leaving your operating system shell - for example, to pipe the output to another process or redirect to a file. This can be done easily by just calling the shell command with the --eval option followed by the JavaScript you want to execute. Just be aware that since the output isn’t being automatically printed by the shell process with this approach, so if you need to print the JSON representation of documents in your queries, you will need to explicitly use the printjson() function to generate correct output. For example:

    $ mongo --eval "db.posts.find().forEach(function(x){printjson(x)})"
    { "_id" : ObjectId("4fbec0b9f3ecac6f43bc1c13"), "x" : 10 }

When writing statements in the shell that leave an open bracket, parenthesis, or quote, hitting enter will prompt you with “…” for more input. So if you need to write a long block of code, you can let it span multiple lines:

    > for(var i=0;i<100;i++){

If you screw up or want to cancel it and start over, just hit enter twice - the entire block of code will be aborted.

A new shell feature available in versions 2.1.x and later is the ability to edit blocks of code using a text editor. Use the “edit” keyword with the name of a function, and it will invoke your editor with the block of source code for that function:

    > edit testfunc 
    // now we get dropped into an editor where we can edit code for the function

    > testfunc // show the source of the function we just wrote
    function testfunc() {
        print("hello world!");
    > testfunc()
    hello world!
comments powered by Disqus