MongoDB shell basics

A short introduction to the most basic things in the MongoDB shell.

Make sure to have MongoDB installed on your system and the daemon running.

To open the shell, type mongo and hit enter.

$ mongo
MongoDB shell version: 2.4.6
connecting to: test

You're now in the context of the database test. To list all the databases, use show dbs.

> show dbs
local	0.078125GB
test	0.203125GB

To create a new database or switch to an already existing one, utilize use.

> use mydb
switched to db mydb

Once you have switched to mydb, you can create a collection. Here we create a new named shapes.

> db.createCollection("shapes")
{ "ok" : 1 }

To prove that a new collection really has been created, you can list all the collections in the database.

> show collections
shapes
system.indexes

When you've created a collection, you can start inserting documents. Here we insert two shapes.

> db.shapes.insert({ "type": "rectangle", "width": 5, "height": 7 })
> db.shapes.insert({ "type": "circle", "radius": 2 })

You can query the collection using the find method, but to simply list all the documents, use find() without a criteria specified.

> db.shapes.find()
{ "_id" : ObjectId("521a6743a8a1ce0d22037037"), "type" : "rectangle", "width" : 5, "height" : 7 }
{ "_id" : ObjectId("521a674aa8a1ce0d22037038"), "type" : "circle", "radius" : 2 }

To make a pretty output, chain pretty() on find().

> db.shapes.find().pretty()
{
  "_id" : ObjectId("521a6743a8a1ce0d22037037"),
  "type" : "rectangle",
  "width" : 5,
  "height" : 7
}
{
  "_id" : ObjectId("521a674aa8a1ce0d22037038"),
  "type" : "circle",
  "radius" : 2
}

Here is how to create an index, in this case on the radius attribute.

db.shapes.ensureIndex({ "radius": 1 })

To list all indexes.

> db.shapes.getIndexes()
[
  {
    "v" : 1,
    "key" : {
      "_id" : 1
    },
    "ns" : "mydb.shapes",
    "name" : "_id_"
  },
  {
    "v" : 1,
    "key" : {
      "type" : 1
    },
    "ns" : "mydb.shapes",
    "name" : "type_1"
  }
]

Droping the collection.

> db.shapes.drop()
true

Droping the database.

> db.dropDatabase()
{ "dropped" : "mydb", "ok" : 1 }

Exiting the shell.

> exit
bye

You can learn more about the MongoDB shell by reading the reference.