Thursday 14 August 2014

mongoDB : Lesson 1 : Creating /dropping databases in MongoDB

Hi Guys,

Fun started here with mongoDB...

1) What is mongoDB database ?
2) How to create mongoDB database ?
3) How to drop mongoDB database ?

mongoDB database :
  • A physical container for collections.[where as in RDBMS it's a collection of related tables]
  • Each database gets its own set of files on the file system. 
  • A single MongoDB server typically has multiple databases.

Lesson 1 : Creating /dropping databases in MongoDB

S.NO
Task To Perform
Command
Sample Output

1

List  all the databases

>show dbs

> show dbs;
admin  (empty)
local  0.078GB
2
Creating Database
Syntax:
>use <databaseName>
Example:
>use myFirstTestDB
> use myFirstTestDB
switched to db myFirstTestDB
3
Check the current database
Syntax : >db
> db;
myFirstTestDB
4
Again list all the databases
>show dbs
> show dbs;
admin  (empty)
local  0.078GB

NOTE :
·         Until and unless you insert some documents into the database by creating a collection you will not see the created database in step 2.
·         To make sure database created you need to create a collection(table in RDBMS)and insert at least one document(records or rows in RDBMS) in it.
5
Insert documents into a collection of database
Syntax :
db.<collectionName>.insert({
key1: value1,key2:value2;
key3:value3
})
>db.student.insert({name:"sadakar",state:"telangana",city:"hyderabad"});
WriteResult({ "nInserted" : 1 })
NOTE:
student is the collection(table in RDMS) name and script between {} is a document(row in RDBMS)

NOTE :
1) Once you press enter button the mongod will create myFirstTestDB database, student collection(table in RDBMS) with the document (rows in RDBMS)permanently
2) There are some other ways to create documents and insert into collections of databases which is not explained in this example.  
6
Now list the all the databases
>show dbs;
> show dbs;
admin          (empty)
local          0.078GB
myFirstTestDB  0.078GB
7
Dropping database
Syntax:
>db.dropDatabase()


NOTE:
1) List databases
2) check current database
3)issue drop function
4) again list the databases
> show dbs;
admin          (empty)
local          0.078GB
myFirstTestDB  0.078GB

> db;
myFirstTestDB

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

> show dbs;
admin  (empty)
local  0.078GB



Learn Quickly by reading my articles and get back to me in comments if you face any issues :-)

Sadakar
BI developer

No comments:

Post a Comment