Mongodb Tutorial
Mongodb Tutorial
MongoDB
4
MongoDB
1. MongoDB ─ Overview
Database
Database is a physical container for collections. Each database gets its own set of files on the
file 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 schema
means 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
5
MongoDB
mysql/sqlplus mongo
Sample Document
Following example shows the document structure of a blog site, which is simply a comma
separated 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. You
can provide _id while inserting the document. If you don’t provide then MongoDB provides a
unique id for every document. These 12 bytes first 4 bytes for the current timestamp, next 3
bytes for machine id, next 2 bytes for process id of MongoDB server and remaining 3 bytes
are simple incremental VALUE.
6
MongoDB
2. MongoDB ─ Advantages
Any relational database has a typical schema design that shows number of tables and the
relationship between these tables. While in MongoDB, there is no concept of relationship.
No complex joins.
Tuning.
Uses internal memory for storing the (windowed) working set, enabling faster access
of data.
7
MongoDB
3. MongoDB ─ Environment
32-bit versions of MongoDB only support databases smaller than 2GB and suitable only for
testing and evaluation purposes.
Now extract your downloaded file to c:\ drive or any other location. Make sure the name of
the extracted folder is mongodb-win32-i386-[version] or mongodb-win32-x86_64-[version].
Here [version] is the version of MongoDB download.
Next, open the command prompt and run the following command.
In case you have extracted the MongoDB at different location, then go to that path by using
command cd FOOLDER/DIR and now run the above given process.
MongoDB requires a data folder to store its files. The default location for the MongoDB data
directory is c:\data\db. So you need to create this folder using the Command Prompt. Execute
the following command sequence.
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.
9
MongoDB
In the command prompt, navigate to the bin directory present in the MongoDB installation
folder. 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 that
the mongod.exe process is running successfully.
Now to run the MongoDB, you need to open another command prompt and issue the following
command.
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 run
MongoDB, you need to issue only commands.
10
MongoDB
In the above installation, 2.2.3 is currently released MongoDB version. Make sure to install
the latest version always. Now MongoDB is installed successfully.
Start MongoDB
sudo service mongodb start
Stop MongoDB
sudo service mongodb stop
Restart MongoDB
sudo service mongodb restart
mongo
MongoDB Help
To get a list of commands, type db.help() in MongoDB client. This will give you a list of
commands as shown in the following screenshot.
11
MongoDB
12
MongoDB
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.
13
MongoDB
4. MongoDB ─ Data Modelling
Data in MongoDB has a flexible schema.documents in the same collection. They 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.
Duplicate the data (but limited) because disk space is cheap as compare to compute
time.
Example
Suppose a client needs a database design for his blog/website and see the differences
between RDBMS and MongoDB schema design. Website has the following requirements.
Every post has the name of its publisher and total number of likes.
Every post has comments given by users along with their name, message, data-time
and likes.
In RDBMS schema, design for above requirements will have minimum three tables.
14
MongoDB
While in MongoDB schema, design will have one collection post and the following structure:
{
_id: POST_ID
title: TITLE_OF_POST,
description: POST_DESCRIPTION,
by: POST_BY,
url: URL_OF_POST,
tags: [TAG1, TAG2, TAG3],
likes: TOTAL_LIKES,
comments: [
{
user:'COMMENT_BY',
message: TEXT,
dateCreated: DATE_TIME,
like: LIKES
},
{
user:'COMMENT_BY',
message: TEXT,
dateCreated: DATE_TIME,
like: LIKES
}
]
}
15
MongoDB
5. MongoDB ─ Create Database
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 would
be as follows:
>use mydb
switched to db mydb
>db
mydb
If you want to check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
Your created database (mydb) is not present in list. To display database, you need to insert
at least one document into it.
>db.movie.insert({"name":"tutorials point"})
>show dbs
local 0.78125GB
mydb 0.23012GB
17
MongoDB
6. MongoDB ─ Drop 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 will
delete 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
>
If you want to delete new database <mydb>, then dropDatabase() command would be as
follows:
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>
>show dbs
local 0.78125GB
test 0.23012GB>
19
MongoDB
7. MongoDB ─ Create Collection
Syntax
Basic syntax of createCollection() command is as follows:
db.createCollection(name, options)
Options parameter is optional, so you need to specify only the name of the collection.
Following is the list of options you can use:
20
MongoDB
While inserting the document, MongoDB first checks size field of capped collection, then it
checks 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 important
options:
In MongoDB, you don't need to create collection. MongoDB creates collection automatically,
when you insert some document.
>db.tutorialspoint.insert({"name" : "tutorialspoint"})
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>
21