Wednesday, 15 July 2015

Mongodb commands to play with databases and collections

Dear Viewers,

This post helps to create and drop database, create and drop collections in mongodb.

I assume that you have mongodb and required JDK version present on your Linux machine. For demonstration purpose, I have used Fedora 17.



1. Export the mongodb path
[pavan@Pavan bin]$ export PATH=/home/pavan/mongodb/bin/:$PATH

2. Check path variable 
[pavan@Pavan bin]$ echo $PATH
/home/pavan/mongodb/bin/:/usr/lib64/ccache:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/home/pavan/.local/bin:/home/pavan/bin
3. Run the mongod server on terminal
[pavan@Pavan ~]$ mongod --dbpath data/db

Note: In this case, I have created separate directory to be used as db directory. If you have also done so, then give the path to that directory while running on mongod server

4. Run the mongo client on other terminal and use this terminal for further commands
[pavan@Pavan ~]$ mongodb/bin/mongo
MongoDB shell version: 3.0.4

5. See existing databases
> show dbs
local  0.078GB
test   0.078GB

Note: In mongodb, default database is 'test'

6. See currently selected database
> db

7. Create new database
> use mydb
switched to db mydb
Explanation: use command create a database if not exists. If it exists, it presents the same

8. See newly created database
> show dbs
local  0.078GB
test   0.078GB

As you can see that newly created database is not shown. To display database, you must have to insert atleast one document into it. 
9. Insert document
> db.mydb.insert({"name":"Pavan Jaiswal"})
WriteResult({ "nInserted" : 1 })
> show dbs
local  0.078GB
mydb   0.078GB
test   0.078GB

10. Drop database
> db.dropDatabase()
{ "dropped" : "mydb", "ok" : 1 }
> show dbs
local  0.078GB
test   0.078GB
It drops the database which is being used

11. Create collection
> use mydb
switched to db mydb
> db.createCollection("mycollection")
{ "ok" : 1 }

Note: In mongodb, you don't need to create collection. Mongodb creates it automatically when you create some document into it. for e.g.

> db.newcollection.insert({"name":"Pavan"})
WriteResult({ "nInserted" : 1 })
12. See the collections
> show collections
mycollection
newcollection
system.indexes

13. Drop collection
> db.newcollection.drop()
true
> show collections
mycollection
system.indexes

In next post we will see how to insert, query, update and delete the documents in mongodb.

Thanks. 

Reference:
1. http://www.tutorialspoint.com/mongodb/index.htm


No comments: