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: testYou're now in the context of the database test. To list all the databases, use show dbs.
> show dbs
local 0.078125GB
test 0.203125GBTo create a new database or switch to an already existing one, utilize use.
> use mydb
switched to db mydbOnce 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.indexesWhen 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()
trueDroping the database.
> db.dropDatabase()
{ "dropped" : "mydb", "ok" : 1 }Exiting the shell.
> exit
byeYou can learn more about the MongoDB shell by reading the reference.