web analytics

Getting started with MONGO shell

New to mongo and have trouble starting???? I shall help with a few basic commands.

Inorder to go to the shell just type mongo


root@abc# mongo
MongoDB shell version: 2.4.5
connecting to: test
>

The default database that will be selected is test, but you need to work with your own databases right, let’s start.

1) Create database.

Creating database is very easy in mongo. You can just create it with the use command. The ‘use’ command selects a database if it exists, or creates a new one if it doesn’t. It is not necessary to provide any data other than db name while creating database.


> use commandtest
switched to db commandtest

2) Create tables (collection)

Unlike mysql, database tables are called collections in mongodb. Once a database is created, you can create a new collection and assign values to it. In next step, we are going to create a collection named “name” and going to insert a value to it.


> db.name.save({name:”abc”})

3) View data – find ()

In order to view the data in collections, you can use the find command as follows. The syntax is db.collectionname.find()


> db.name.find()
{ “_id” : ObjectId(“52133000e1d4f8f05404a741”), “name” : “abc” }

4) Show databases

Once a database and collection are saved, you can show the databases as follows. You can see the database that we created ‘commandtest’ also listed along with other databases.


> show databases
admin   (empty)
commandtest     0.203125GB
db_list 9.94921875GB
dev     0.078125GB
dummy_data      13.947265625GB
local   0.078125GB

 

5) Show collections

After selecting a database, if you want to see the collections inside the database, you can use following.

> use commandtest
switched to db commandtest
> show collections
name
system.indexes

The collection name is “name”. The collection system.indexes is default.

You can quit the mongo shell by pressing Ctl+C

A simple script to create test database and data can be found here.

How mongo database can be backed up and restored can be found here.

 

Leave a reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>