Overview - The MongoDB Interactive Shell

Running the Shell

The interactive shell is included in the standard MongoDB distribution. To start the shell, go into the root directory of the distribution and type

./bin/mongo

It might be useful to add mongo_distribution_root/bin to your PATH so you can just type mongo from anywhere.

If you start with no parameters, it connects to a database named "test" running on your local machine on the default port (27017). You can see the db to which you are connecting by typing db:

./mongo
type "help" for help
> db
test

You can pass mongo an optional argument specifying the address, port and even the database to initially connect to:

./mongo foo connects to the foo database on your local machine
./mongo 192.168.13.7/foo connects to the foo database on 192.168.13.7
./mongo dbserver.mydomain.com/foo connects to the foo database on dbserver.mydomain.com
./mongo 192.168.13.7:9999/foo connects to the foo database on 192.168.13.7 on port 9999

.mongorc.js

1.9.1+

When the shell is launched, it checks the user's home directory for a javascript file named .mongorc.js. If this file is found, its contents are interpreted and run by the shell prior to displaying the prompt for the first time. This allows the user to define variables, customize the prompt, or update information that they would like updated every time they launch a shell. This functionality can be overridden with the --norc flag. It should be noted that if a file is specified to be executed by the shell, the rc file will not be run until after that file has completed.

Operations

Help

> help                          // top level help
> db.help()                     // help on db-specific methods
> db.mycollection.help()        // help on collection methods
> db.mycollection.find().help() // cursor help

Select Database

The following are three basic commands that provide information about the available databases, and collections in a given database.

show dbs displays all the databases on the server you are connected to
use db_name switches to db_name on the same server
show collections displays a list of all the collections in the current database

Querying

mongo uses a JavaScript API to interact with the database. Because mongo is also a complete JavaScript shell, db is the variable that is the current database connection.

To query a collection, you simply specify the collection name as a property of the db object, and then call the find() method. For example:

db.foo.find();

This will display the first 10 objects from the foo collection. Typing it after a find() will display the next 10 subsequent objects.

By setting the shellBatchSize you can change this:
DBQuery.shellBatchSize = #
If the shell does not accept the collection name (for example if it starts with a number, contains a space etc), use
db['foo'].find()
instead.

Inserting

In order to insert data into the database, you can simply create a JavaScript object, and call the save() method. For example, to save an object {name: "sara"} in a collection called foo, type:

db.foo.save({ name : "sara"});

Note that MongoDB will implicitly create any collection that doesn't already exist.

Updating

Let's say you want to change someone's address. You can do this using the following mongo commands:

person = db.people.findOne( { name : "sara" } );
person.city = "New York";
db.people.save( person );

Deleting

db.foo.drop() drop the entire foo collection
db.foo.remove() remove all objects from the collection
db.foo.remove( { name : "sara" } ) remove objects from the collection where name is sara

Indexes

db.foo.getIndexKeys() get all fields that have indexes on them
db.foo.ensureIndex({ _field_ : 1 }) create an index on field if it doesn't exist

Open Additional Connections

You can use the following commands to open additional connections (normally you don't need to do this, but might from a script):

conn = new Mongo(host);
db = conn.getDB(dbname);
db.auth(username,password);

where host is a string that contains either the name or address of the machine you want to connect to (e.g. "192.168.13.7") or the machine and port (e.g. "192.168.13.7:9999"). Note that host in an optional argument, and can be omitted if you want to connect to the database instance running on your local machine. (e.g. conn = new Mongo() )

Alternatively you can use the connect helper method:

> db = connect("localhost:27020/mytestdb"); // example with a nonstandard port #

Working from the Prompt

Line Continuation

If a line contains open '(' or '{' characters, the shell will request more input before evaluating:

> function f() {
... x = 1;
... }
>

You can press Ctrl-C to escape from "..." mode and terminate line entry.

Key Shortcuts

  • up/down array for command history
  • in v1.9+ some basic emacs keystrokes work
  • ctrl-l to clear the screen
  • tab for auto-complete (newer versions only)
  • ctrl-c to exit, or to break out of line continuation mode

Custom Prompt

1.9.1+

The shell's prompt can be customized by creating variable 'prompt' in the shell. It can be any arbitrary javascript, including a function that returns a string. This flexibility allows for additional information to be displayed in the prompt. For example, to have a prompt that contains the number of commands issued, type:

> cmdCount = 1;
> prompt = function() {
... return (cmdCount++) + "> ";
... }
1> command
2> anothercommand
3>

To make the prompt look a bit more familiar, we can make it database@host$:

> host = db.serverStatus().host; \\ since host should not change
> prompt = function() {
... return db+"@"+host+"$ ";
... }
admin@mylaptop.local$ use monkeys
switched to db monkeys
monkeys@mylaptop.local$

You could use the prompt to do a bit of database monitoring as well:

> prompt = function() {
... return "Uptime:"+db.serverStatus().uptime+" Files:"+db.stats().objects+" > ";
... }
Uptime:5897 Files:6 > db.monkeys.save({name : "James"});
Uptime:5948 Files:7 >

Using a real editor

2.1.0+

We've added a feature to allow you edit larger values including functions using your editor of choice. Just run edit nameOfVariableOrFunction and we will open whatever editor you have defined in your $EDITOR environment variable. Make sure that you save the file when editing. If you wish to discard your changes, you can either not save or make your editor exit with an error (:cq in Vim or (kill-emacs 1) in Emacs).

$ EDITOR=vim mongo --nodb
MongoDB shell version: 2.1.0-pre-
> function f() {}
> edit f
> f
function f() {
    print("this really works");
}
> f()
this really works
> o = {}
{ }
> edit o
> o
{ "soDoes" : "this" }
>

It is possible that the code in functions will be slightly modified by the JavaScript compiler when you try to edit it again. For example it may convert 1+1 in to 2 and strip out comments. The actual changes will vary based on the version of JavaScript used, but should not effect the semantics of the code, only its appearance.

Some Notes on Datatypes in the Shell

Numbers

By default, the shell treats all numbers as floating-point values. You have the option to work with 64 bit integers by using a class built into the shell called NumberLong() If you have long/integer BSON data from the database you may see something like this:

"bytes" : {
   "floatApprox" : 575175
}

or something like this for larger numbers (in 1.6+):

{..., "bytes" : NumberLong("5284376243087482000") ,...}

Note that prior to 1.6 long numbers might be displayed like this:

"bytes" : {
   "floatApprox" : 5284376243087482000,
   "top" : 1230364721,
   "bottom" : 4240317554
}

In addition, setting/incrementing any number from javascript will (most likely) change the data type to a floating point value.

Here is an example of creating a document with a long field:

doc = { field: new NumberLong("123212313")}

Dates

The Date() function returns a string and a "new Date()" will return an object (which is what you should use to store values).

> Date()
Sun May 02 2010 19:07:40 GMT-0700 (Pacific Daylight Time)
> new Date()
"Sun May 02 2010 19:07:43 GMT-0700 (Pacific Daylight Time)"
> typeof(new Date())
object
> typeof(Date())
string

newer (1.7+) versions print this

> new Date()
ISODate("2010-11-29T19:41:46.730Z")
> ISODate("2010-11-29T19:41:46.730Z")
ISODate("2010-11-29T19:41:46.730Z")

As you can see, ISODate is a thin wrapper around the Date constructor to fix some of it's shortcomings. It returns a normal Date object with all of the normal methods that javascript Date methods support. We have also changed the way that Date objects print to make sure that they don't look like strings and that if you copy and paste the output you get the same object.

BinData

The BSON BinData datatype is represented via class BinData in the shell. Run help misc for more information.

> new BinData(2, "1234")
BinData(2,"1234")

See Also


Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

PLEASE POST QUESTIONS IN THE USER GROUPS FORUM. Post non-question comments and helpful hints here.

blog comments powered by Disqus