Database Lab Manual
Database Lab Manual
Database Lab Manual
PAGE
EX.NO EXPERIMENT NAME NO
4. Distributed Database
5. Query Processing
6. Xml Schema
7.
Case Study-Mongo DB
Exercise: 1
Date: DDL, DML, DQL, TCL
Aim:
Procedure:
SQL> create table employee1(eno number(15), ename varchar(15), salary number(16), dob
date);
Table created.
ENO NUMBER(15)
ENAME VARCHAR2(20)
SALARY NUMBER(16)
DESGN VARCHAR2(20)
ENAME
kavi
keerthi
DISPLAY EMPLOYEE NAMES WHO HAVE NAMES ENDING WITH LETTER ‘K’
SALARY
35000
32000
Transaction Control Language (TCL)
1 ravi
2 aarav
3 kumar
CREATE SAVEPOINT
SQL> savepoint s1;
Savepoint created.
COMMIT
SQL> commit; set auto commit =1;
Commit complete.
1 ravi
2 aarav
ROLLBACK
SQL> rollback;
Rollback complete.
1 ravi
2 aarav
3 kumar
Result:
Thus the all DDL, DML, DQL, TCL commands are executed and verified successfully.
Exercise: 2
Date: Simple Queries, Nested Queries, Sub Queries and
Joins
Aim:
To execute and verify the SQL commands using Simple Queries, Nested Queries, Sub Queries
and Joins.
Procedure:
SQL> create table customers (id int , name varchar(20) , age int , address varchar(20) , salary
numeric(5)) ;
Table created.
SQL> select *from customers where id in (select id from customers where salary > 10000);
1 ramesh 35 US 5000
2 aarav 2 canada 25000
SQL> update customers set salary = salary * 0.50 where age in (select age from customers where
age = 2 );
1 row updated.
SQL> create table customers_bkp (id int , name varchar(20) , age int , address v
archar(20) , salary numeric(5)) ;
Table created.
SQL> insert into customers_bkp select * from customers where id in (select id from customers) ;
2 rows created.
1 ramesh 35 US 2500
2 aarav 2 canada 12500
SQL> delete from customers where age in (select age from customers_bkp where age = 35);
1 row deleted.
Nested Queries:
ID FIRSTNAME
100 ragul
ID NAME
101 anjali bhaguat
102 sekar gupta
SQL> select id, (select name from mathsgroup where id=101) as name, age, subject, games from
studentdetail where id=101;
Joins:
ID NAME
1 Private
2 Money
3 Ninja
4 Sun
ID NAME
1 Road
2 Private
3 Dark
4 Ninja
ID NAME ID NAME
1 Private 2 Private
3 Ninja 4 Ninja
ID NAME ID NAME
1 Road
1 Private 2 Private
3 Dark
3 Ninja 4 Ninja
2 Money
4 Sun
6 rows selected.
ID NAME ID NAME
1 Private 2 Private
3 Ninja 4 Ninja
2 Money
4 Sun
SQL> SELECT * FROM TABLE_A LEFT OUTER JOIN TABLE_B ON
TABLE_A.NAME=TABLE_B.NAME WHERE TABLE_B.ID IS NULL;
ID NAME ID NAME
2 Money
4 Sun
ID NAME ID NAME
1 Road
3 Dark
2 Money
4 Sun
Result
Thus the SQL commands using Simple Queries, Nested Queries, Sub Queries and Joins are
executed and verified successfully.
Exercise: 3
Date: Views, Sequences, Synonyms
Aim:
To execute and verify the SQL commands for Views, Sequences and synonyms.
Procedure:
VIEWS
1 kavitha 20000
2 prabu 40000
1 kavitha 20000
2 prabu 40000
1 kavitha 20000
2 prabu 40000
3 naveena 27000
3 rows selected.
1 kavitha 20000
2 prabu 40000
3 naveena 27000
3 rows selected.
1 kavitha 20000
2 prabu 40000
3 kayal 27000
3 rows selected.
1 kavitha 20000
2 prabu 40000
3 kayal 27000
3 rows selected.
1 kavitha 20000
2 prabu 40000
2 rows selected.
1 kavitha 20000
2 prabu 40000
2 rows selected.
SQL> create view empview as select eno,ename from employee with read only;
View created.
ENO ENAME
1 kavitha
2 prabu
2 rows selected.
ERROR at line 1:
ORA-01733: virtual column not allowed here
SEQUENCE
SQL> /
NEXTVAL
NEXTVAL
1
SQL> /
NEXTVAL
2
SQL> /
NEXTVAL
1
SQL> /
NEXTVAL
SYNONYMS
1 kavitha 25000
2 prabu 26000
2 rows selected.
INDEX
SQL> create index a_index on employee(ename);
Index created.
RESULT:
Thus execute and verify the SQL commands for Views, Sequences and synonyms.
Exercise:4
Distributed Database
Date:
AIM
To implement distributed database for a book store using four different sites.
DISTRIBUTED DATABASE:
A distributed database is a database in which storage devices are not all attached to a
common processing unit such as the CPU, controlled by a distributed database management
system. Data may be stored in multiple computers, located in same physical location; or may be
dispersed over a network of interconnected computers.
Fragmentation
The relation is fragmented into several relations in such a way that the actual relation
could be reconstructed from the fragments and then the fragments are scattered to different
locations. Two schemes of fragmentation: Horizontal fragmentation - splits the relation by
assigning each tuple of relation to one or more fragments. Vertical fragmentation - splits the
relation by decomposing the schema of relation.
Site 1:
Table Creation
SQL> create table books as (select * from exam21.books where price<=20);
Table created.
no rows selected
ISBN NUMBER(10)
AUTHOR VARCHAR2(20)
TOPIC VARCHAR2(20)
TOTALSTOCK NUMBER(5)
PRICE NUMBER(10)
no rows selected
Grant Permission
SQL> grant all on books to exam32;
Grant succeeded.
Grant succeeded.
Grant succeeded.
Table Creation
SQL> create table bookstore as (select * from exam21.bookstore where zip <=25000);
Table created.
SQL> commit;
Commit complete.
Grant Permission
SQL> grant all on bookstore to exam32;
Grant succeeded.
Grant succeeded.
Grant succeeded.
SQL> commit;
Commit complete.
Site 2:
Table Creation
SQL> create table books as (select * from exam21.books where price between 20 and 50);
Table created.
1002 kalaiselvi ds 25 50
SQL> commit;
Commit complete.
Grant Permission
SQL> grant all on books to exam31;
Grant succeeded.
Grant succeeded.
Grant succeeded.
Table Creation
SQL> create table bookstore as (select * from exam21.bookstore where zip between 25001 and
50000);
Table created.
SQL> commit;
Commit complete.
Grant Permission
SQL> grant all on bookstore to exam31;
Grant succeeded.
Grant succeeded.
SQL> grant all on bookstore to exam34;
Grant succeeded.
1002 kalaiselvi ds 25 50
Site 3:
Table Creation
SQL> create table books as (select * from exam21.books where price between 51 and 100);
Table created.
1 row created.
SQL> commit;
Commit complete.
Grant Permission
SQL> grant all on books to exam31;
Grant succeeded.
Grant succeeded.
Grant succeeded.
Table Creation
SQL> create table bookstore as(select * from exam21.bookstore where zip between 50001 and
75000);
Table created.
SQL> commit;
Commit complete.
Grant Permission
SQL> grant all on bookstore to exam31;
Grant succeeded.
Grant succeeded.
Site 4:
Table Creation
SQL> create table books as (select * from exam21.books where price>100);
Table created.
SQL> commit;
Commit complete.
Grant Permission
SQL> grant all on books to exam31;
Grant succeeded.
Grant succeeded.
Grant succeeded.
Table Creation
SQL> create table bookstore as (select * from exam21.bookstore where zip between 75001 and
99999);
Table created.
SQL> select * from bookstore;
SQL> commit;
Commit complete
Grant Permission
SQL> grant all on bookstore to exam31;
Grant succeeded.
Grant succeeded.
Grant succeeded.
RESULT:
Thus the above program for distributed database will be executed successfully.
Exercise: 5
Query Processing
Date:
AIM:
To implement Query Optimizer with Relational Algebraic expression construction and
execution plan generation for choosing an efficient execution strategy for processing the various
query in employee table.
QUERY PROCESSING:
Query processing is a set of activities involving in getting the result of a query expressed
in a high-level language. These activities include parsing the queries and translate them
into expressions. The cost of processing of query is dominated by the disk access.
EXPLAIN PLAN output shows how Oracle runs the SQL statement when the statement was
explained. The execution and explain plan happen on different databases. Even if the schemas
are the same, the optimizer can choose different execution plans if the costs are different.
STEP1:
Step 5:Type the required password and re-enter it then click next
STEP 2:
password as “admin”
SQL> connect
Connected.
STEP 3:
Table created.
SQL>descbranch_office;
STREET VARCHAR2(20)
CITY VARCHAR2(20)
POSTCODE NUMBER(10)
STEP 4:
Table created.
SQL>descemployee_details;
SEX VARCHAR2(10)
SALARY NUMBER(10)
EXP NUMBER(5)
POSITION VARCHAR2(20)
BRANCHNO NUMBER(15)
STEP 5:
1 row created.
SQL> /
1 row created.
SQL> /
Enter value for branchno: 1003
1 row created.
STEP 6:
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
STEP 7:
Table created.
Utlxpaln is a script to create plan_table by default.
It stores the result of each query.
This command appends the results of each query into the plan_table.
Inordertoshow the result of current query we want to delete the plan_table
manually.
STEP 8:
STEP 9:
RESULT:
Thus the above program for implementation of query processing was executed
successfully.
Exercise:6
XML SCHEMA
Date:
AIM:
To design XML Schema for the company database of Department, Employee, and Project
and execute a query using XPATH, XQUERY and implement a storage structure for storing
XML.
XML:
Extensible Markup Language (XML) is an abbreviated version of Standard Generalized
Markup Language (SGML), for the exchange of structured documents over the Internet. Unlike
HTML, XML readily enables the definition, transmission, validation, and interpretation of data
between differing computing platforms and applications.
XML SCHEMA:
An XML schema is a single file or collection of files that serve as the framework for
defining the data content, format and structure of an XML document. A well written schema
expresses agreed upon vocabularies and allows computers to validate the data against the rules
written to describe the data. It provides a means for defining the structure and content of XML
documents.
XPath:
XPath is syntax for accessing parts of an XML document. It uses a path structure to
define XML elements. It has a library of standard functions. It is one of the main components of
XQuery and XSLT.
XQuery:
XQuery was devised primarily as a query language for data stored in XML form. So its
main role is to get information out of XML databases — this includes relational databases that
store XML data, or that present an XML view of the data they hold.
TOOLS REQURIED :
XmlValidator - XML Schema
BaseX - Xpath and Xquery
MYSQL above 5.1 - Storage structure for storing XML database
PROCEDURE:
1. Create XML file for department, employee and project.
2. Validate the XML file using Schema.
3. Xpath be used to locate the particular path in a file.
4. Implemenet the queries using Xquery and XPath.
5. The structure of Xquery is “FLWOR” is For – Let – Where – Order by – Return.
6. Store XML document into MySql Database using Load XML file.
XML AND XML SCHEMA FOR COMPANY DATABASE:
Company database contains the following tables
Department
Company
Employee
DEPARTMENT:
Department table contains the following fields in XML file
deptName
deptNo
deptManagerSSN
deptManagerStart Date
deptLocation
XML for Department:
depart.xml
<?xml version="1.0" encoding="UTF-8"?>
<company xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:noNamespace
SchemaLocation="depart.xsd">
<dept name="Research">
<ditem deptno="1"
deptname="Research"
deptmanagerssn="empssn1"
deptmanagerstartdate="1997-07-01"
deptlocation="Coimbatore"/>
</dept>,
<dept name="Adminstration">
<ditem deptno="2"
deptname="Admistration"
deptmanagerssn="empssn2"
deptmanagerstartdate="1999-11-19"
deptlocation="Chennai"/>
</dept>,
<dept name="Purchase">
<ditem deptno="3"
deptname="Purchase"
deptmanagerssn="empssn3"
deptmanagerstartdate="1987-05-09"
deptlocation="Bangalore"/>
</dept>,
<dept name="Sales">
<ditem deptno="4"
deptname="Sales"
deptmanagerssn="empssn4"
deptmanagerstartdate="1995-05-25"
deptlocation="Mumbai"/>
</dept>
<dept name="Financial">
<ditem deptno="5"
deptname="Financial"
deptmanagerssn="empssn5"
deptmanagerstartdate="1991-12-20"
deptlocation="Chennai"/>
</dept>
</company>
EMPLOYEE:
Employee table contains the following fields
empName
empSSN
empSex
empSalary
empBirthDate
empDeptNo
empSupervisorSSN
empAddress
empWorksOn
XML for Employee:
employ.xml
<?xml version="1.0" encoding="UTF-8"?>
<employee department="Research">
<eitem empname="Vijay"
empssn="empssn1"
empsex="male"
empsalary="50000"
empbirthdate="1987-10-19"
empdeptno="1"
empsupervisorssn="0"
empaddress="address1"
empworkon="25"/>
<eitem empname="Shiva"
empssn="empssn6"
empsex="female"
empsalary="24000"
empbirthdate="1990-10-19"
empdeptno="1"
empsupervisorssn="empssn1"
empaddress="address1"
empworkon="7"/>
<eitem empname="Thomas"
empssn="empssn10"
empsex="female"
empsalary="25000"
empbirthdate="1991-09-30"
empdeptno="1"
empsupervisorssn="empssn1"
empaddress="address1"
empworkon="8"/>
</employee>,
<employee department="Adminstration">
<eitem empname="Moni"
empssn="empssn2"
empsex="female"
empsalary="47000"
empbirthdate="1989-01-01"
empdeptno="2"
empsupervisorssn="0"
empaddress="address2"
empworkon="25"/>
</employee>,
<employee department="Purchase">
<eitem empname="Gowtham"
empssn="empssn3"
empsex="male"
empsalary="30000"
empbirthdate="1991-04-09"
empdeptno="3"
empsupervisorssn="0"
empaddress="address3"
empworkon="9"/>
<eitem empname="JaiVidhya"
empssn="empssn7"
empsex="female"
empsalary="27000"
empbirthdate="1991-04-09"
empdeptno="3"
empsupervisorssn="empssn3"
empaddress="address3"
empworkon="21"/>
</employee>,
<employee department="Sales">
<eitem empname="Uma"
empssn="empssn4"
empsex="female"
empsalary="37000"
empbirthdate="1991-04-09"
empdeptno="4"
empsupervisorssn="0"
empaddress="address4"
empworkon="14"/>
</employee>,
<employee department="Finacial">
<eitem empname="Praveen"
empssn="empssn5"
empsex="male"
empsalary="32000"
empbirthdate="1991-04-09"
empdeptno="5"
empsupervisorssn="0"
empaddress="address2"
empworkon="12"/>
<eitem empname="Sathish"
empssn="empssn9"
empsex="male"
empsalary="32000"
empbirthdate="1991-17-07"
empdeptno="5"
empsupervisorssn="empssn5"
empaddress="address9"
empworkon="11"/>
</employee>
</employees>
<xs:complexType mixed="true">
<xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="eitem">
<xs:complexType>
</xs:complexType>
</xs:element>
</xs:schema>
PROJECT:
Project table contains the following fields in XML
projName
projNo
projLocation
projDeptNo
projWorker
XML for Project:
proj.xml
<?xml version="1.0" encoding="UTF-8"?>
<project no="1">
<prjitem prjno="1"
prjname="Cloud Computing"
prjlocation="location1"
prjdeptno="1"
prjwrk="5"/>
</project>,
<project no="2">
<prjitem prjno="2"
prjname="DataBase"
prjlocation="location2"
prjdeptno="2"
prjwrk="7"/>
</project>
<project no="3">
<prjitem prjno="3"
prjname="Networks"
prjlocation="location3"
prjdeptno="3"
prjwrk="11"/>
</project>,
<project no="4">
<prjitem prjno="4"
prjname="Management System"
prjlocation="location4"
prjdeptno="4"
prjwrk="6"/>
</project>,
<project no="5">
<prjitem prjno="5"
prjname="Accounting"
prjlocation="location5"
prjdeptno="5"
prjwrk="17"/>
</project>
</projects>
<xs:element name="projects">
<xs:complexType mixed="true">
<xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="project">
<xs:complexType>
<xs:sequence>
<xs:element ref="prjitem"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="prjitem">
<xs:complexType>
</xs:complexType>
</xs:element>
</xs:schema>
</ul>
</body>
</html>
ii. Retrieve the employee name, supervisor name and employee salary for each employee
who works in the Research Department.
<html>
<body>
<h1>Companys</h1>
<ul>
{
for $x in doc("depart.xml")//ditem[@deptname = "Research"],
$y in doc("employ.xml")//eitem
where $y/@empsupervisorssn = $x/@deptmanagerssn
return <li Employeename="{$y/@empname}" Employeesalary="{$y/@empsalary}" >
{
attribute Suprevisior
{
for $z in doc("employ.xml")//eitem
where $z/@empssn = $x/@deptmanagerssn
return $z/@empname
}
}</li>
}
</ul>
</body>
</html>
OUTPUT :
<html>
<body>
<h1>Companys</h1>
<ul>
<li> Employeename="Shiva" Employeesalary="24000" Suprevisior="Vijay" </li>
<li> Employeename="Thomas" Employeesalary="25000" Suprevisior="Vijay" </li>
</ul>
</body>
</html>
iii. Retrieve the project name, controlling department name, number of employees and
total hours worked per week on the project for each project.
<html>
<body>
<h1>Company</h1>
<ul>
{
for $d in distinct-values(doc("employ.xml")//eitem/@empdeptno),
$p in doc("proj.xml")//prjitem[@prjdeptno=$d],
$de in doc("depart.xml")//ditem[@deptno=$d]
let $items := doc("employ.xml")//eitem[@empdeptno=$d]
where $p/@prjdeptno = $de/@deptno
order by $de/@deptno
return <li Projectname="{$p/@prjname}" DepartmentName="{$de/@deptname}"
Deptno="{$d}" TotalHrWorked="{$p/@prjwrk}" empNoEmp="{count($items)}" />
}
</ul>
</body>
</html>
OUTPUT:
<html>
<body>
<h1>Company</h1>
<ul>
<li> Projectname="Cloud Computing" DepartmentName="Research" Deptno="1"
TotalHrWorked="5" empNoEmp="3"</li>
<li>Projectname="DataBase" DepartmentName="Admistration" Deptno="2"
TotalHrWorked="7" empNoEmp="1"</li>
<li> Projectname="Networks" DepartmentName="Purchase" Deptno="3"
TotalHrWorked="11" empNoEmp="2"</li>
<li> Projectname="Management System" DepartmentName="Sales" Deptno="4"
TotalHrWorked="6" empNoEmp="1"</li>
<li> Projectname="Accounting" DepartmentName="Financial" Deptno="5"
TotalHrWorked="17" empNoEmp="2"</li>
</ul>
</body>
</html>
iv. Retrieve the project name, controlling department name, number of employees and
total hours worked per week on the project for each project with more than one employee
working on it
<html>
<body>
<h1>Company</h1>
<ul>
{
for $d in distinct-values(doc("employ.xml")//eitem/@empdeptno),
$p in doc("proj.xml")//prjitem[@prjdeptno=$d],
$de in doc("depart.xml")//ditem[@deptno=$d]
let $items := doc("employ.xml")//eitem[@empdeptno=$d]
where $p/@prjdeptno = $de/@deptno
order by $de/@deptno
return <li Projectname="{$p/@prjname}" DepartmentName="{$de/@deptname}"
Deptno="{$d}" TotalHrWorked="{$p/@prjwrk}" empNoEmp="{count($items)>1}" />
}
</ul>
</body>
</html>
OUTPUT :
<html>
<body>
<h1>Company</h1>
<ul>
</ul>
</body>
</html>
b. Implement a storage structure for storing XML database and test with the
above schema.
TO CREATE DATABASE
TO USE DATABASE
Database changed
+ +
| Tables_in_xml |
+ +
| dept |
| emp |
| proj |
+ +
+ + + + + +
+ + + + + +
+ + + + + + +
+ + +
+ + + + + + +
+ + +
| address1 | 25 |
| address1 | 7 |
| address1 | 8 |
| address2 | 25 |
| address3 | 9 |
| address3 | 21 |
| address4 | 14 |
| address2 | 12 |
| address9 | 11 |
+ + + + + + +
+ + +
+ + + + + +
| DataBase |2 | location2 |2 |7 |
| Networks | 3 | location3 |3 | 11 |
| Accounting |5 | location5 |5 | 17 |
+ + + + + +
RESULT:
Thus the XML Schema for the company database of Department, Employee, and Project using
XPATH, XQUERY and storage structure was implemented successfully
CASE STUDY-MONGO DB
introduction
MongoDB is a cross-platform, document oriented database that provides, high performance,high
availability, and easy scalability. MongoDB works on concept of collection and document.
Database
Database is a physical container for collections. Each database gets its own set of files on thefile
system. A single MongoDB server typically has multiple databases.
Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A
collection exists within a single database. Collections do not enforce a schema. Documents within
a collection can have different fields. Typically, all documents in a collection are of similar or
related purpose.
Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schemameans
that documents in the same collection do not need to have the same set of fields or structure, and
common fields in a collection's documents may hold different types of data.
The following table shows the relationship of RDBMS terminology with MongoDB.
RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
Column Field
Mysqld/Oracle Mongod
mysql/sqlplus Mongo
7
Sample Document
Following example shows the document structure of a blog site, which is simply a commaseparated key value
pair.
{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2011,1,20,2,15),
like: 0
},
{
user:'user2',
message: 'My second comments',
dateCreated: new Date(2011,1,25,7,45),
like: 5
}
]
}
_id is a 12 bytes hexadecimal number which assures the uniqueness of every document.
Youcan provide _id while inserting the document. If you don’t provide then MongoDB provides aunique id for
every document. These 12 bytes first 4 bytes for the current timestamp, next 3bytes for machine id, next 2 bytes for
process id of MongoDB server and remaining 3 bytes are simple incremental VALUE.
2. MONGO DB -ADVANTAGE
Any relational database has a typical schema design that shows number of tables and therelationship between these
tables. While in MongoDB, there is no concept of relationship.
No complex joins.
Deep query-ability. MongoDB supports dynamic queries on documents using a document-based query
language that's nearly as powerful as SQL.
Tuning.
Uses internal memory for storing the (windowed) working set, enabling faster accessof data.
C:\>md data
C:\md data\db
If you have to install the MongoDB at a different location, then you need to specify an alternate path for \data\db by
setting the path dbpath in mongod.exe. For the same, issue the following commands.
In the command prompt, navigate to the bin directory present in the MongoDB installationfolder. Suppose my
installation folder is D:\set up\mongodb
C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"
This will show waiting for connections message on the console output, which indicates thatthe mongod.exe process is
running successfully.
Now to run the MongoDB, you need to open another command prompt and issue the followingcommand.
D:\set up\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.6
connecting to: test
>db.test.save( { a: 1 } )
>db.test.find()
{ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 }
>
This will show that MongoDB is installed and run successfully. Next time when you runMongoDB, you need
to issue only commands.
Start MongoDB
sudo service mongodb start
Stop MongoDB
Restart MongoDB
sudo service mongodb restart
To use MongoDB run the following command.
mongo
This will connect you to running MongoDB instance.
MongoDB Help
To get a list of commands, type db.help() in MongoDB client. This will give you a list ofcommands as shown in
the following screenshot.
MongoDB Statistics
To get stats about MongoDB server, type the command db.stats() in MongoDB client. This will show the database
name, number of collection and documents in the database. Output of the command is shown in the following
screenshot.
Syntax
Basic syntax of use DATABASE statement is as follows:
use DATABASE_NAME
Example
If you want to create a database with name <mydb>, then use DATABASE statement wouldbe as follows:
>use mydb
switched to db mydb
To check your currently selected database, use the command db
>db
mydb
If you want to check your databases list, use the command show dbs.
>show dbs
test 0.23012GB
local 0.78125GB
>db.movie.insert({"name":"tutorials point"})
test 0.23012GB
>show dbs
local 0.78125GB
Your created database (mydb) is not present in list. To display database, you need to insertat least one document into
it
In MongoDB default database is test. If you didn't create any database, then collections willbe stored in test database.
In this chapter, we will see how to drop a database using MongoDB command.
Syntax
Basic syntax of dropDatabase() command is as follows:
db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it willdelete default 'test'
database.
Example
First, check the list of available databases by using the command, show dbs.
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
>
The createCollection() Method
MongoDB db.createCollection(name, options) is used to create collection.
Syntax
Basic syntax of createCollection() command is as follows:
db.createCollection(name, options)
In the command, name is name of collection to be created. Options is a document and isused to specify
configuration of collection.
Options parameter is optional, so you need to specify only the name of the collection.Following is the list of
options you can use:
While inserting the document, MongoDB first checks size field of capped collection, then itchecks max field.
Examples
Basic syntax of createCollection() method without options is as follows:
>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>
You can check the created collection by using the command show collections.
>show collections
mycollection
system.indexes
The following example shows the syntax of createCollection() method with few importantoptions:
>db.tutorialspoint.insert({"name" : "tutorialspoint"})
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>