Mongodb PDF
Mongodb PDF
High performance.
High availability.
Easy scalability.
Although it is 100 times faster than the traditional database but it is early to
say that it will broadly replace the traditional RDBMS. But it may be very useful
in term to gain performance and scalability.
A 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.
RDBMS and MongoDB
RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
column Field
Table Join Embedded Documents
Primary Key Primary Key (Default key _id
provided by MongoDB itself)
Database Server and Client
mysqld/Oracle mongod
mysql/sqlplus mongo
Install MongoDB On Windows
To install MongoDB on Windows, first download the latest release of MongoDB
from https://www.mongodb.com/download-center.
Where to use MongoDB
Enter the required details, select the Server tab, in it you can choose the version of
MongoDB, operating system and, packaging as:
Where to use MongoDB
Now install the downloaded file, by default, it will be installed in the folder C:\Program
Files\.
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
Where to use MongoDB
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.
MongoDB Architecture
Database
Architecture : -
Document Container
Mongo - 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.
Mongo – Database creation
There is no create database command in MongoDB. Actually, MongoDB do not provide any
command to create database.
In MongoDB you don't need to create a database manually because MongoDB will create it
automatically when you save the value into the defined collection at first time.
use DATABASE_NAME
If there is no existing database, the following command is used to create a new database.
If the database already exists, it will return the existing database.
Mongo – Database creation
Use SampleDB
DB (DB command will give return SampleDB )
Show databases / show dbs (will list all data bases in the server)
Created database "Sampledb" will be in the list only after inserting a
document in it.
db.emp.insert({name:"uma"})
WriteResult({ "nInserted" : 1 })
Mongo –Droping Database
> db.dropdatabase
test.dropdatabase
command will delete the selected database.
In the case we have not selected any database, it will delete default "test" database.
> db.dropdatabase
sample1.dropdatabase
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
sample1 0.000GB
test 0.000GB
Mongo – Database- Collection
In Mongo Collections will create automatically when insert the data into it.
db.sample23.insert({“name”:”uma”})
Insert command will insert the data if collection exist else it will create a new Collection and
insert the data in it.
MongoDB Datatypes
Data Types Description
String String is the most commonly used datatype. It is used to store data. A string must
be UTF 8 valid in mongodb.
Integer Integer is used to store the numeric value. It can be 32 bit or 64 bit depending on
the server you are using.
Boolean This datatype is used to store boolean values. It just shows YES/NO values.
Arrays This datatype is used to store a list or multiple values into a single key.
> db.emp.insert({"name":"Uma"})
WriteResult({ "nInserted" : 1 })
> db.emp.find()
{ "_id" : ObjectId("5f9aff2ddb99a0cb0f6678cf"), "name" : "Uma" }
Mongo – Drop Collection
In MongoDB, the db.collection.insert() method is used to add or insert new documents into a
collection in your database.
db.emp.insert(
... {
... name: "Chaaru",
... details: {
... age: "19 years",
... standard: "BE first year"
... },
... Batch: [ { size: "Small", qty: 15 }, { size: "Medium", qty: 25 } ],
... category: "Computer Science"
... }
... )
WriteResult({ "nInserted" : 1 })
MongoDB insert multiple documents
db.student.find({},{"name":1,"age":1,_id:0})
Note:
In Mongo the _id field is always displayed while executing find() method, to hide the field set
it as 0.
MongoDB -Limit
To limit the records in MongoDB, you need to use limit() method. The method accepts one
number type argument, which is the number of documents that you want to be displayed.
db.COLLECTION_NAME.find().limit(NUMBER)
db.emp.find().limit(5);
{ "name" : "Anu", "age" : 12 }
{ "name" : "Deepa", "age" : 24 }
{ "name" : "Chaaru", "age" : 35 }
{ "name" : "Chaaru", "age" : 35 }
{ "name" : "David", "age" : 35 }
MongoDB - Skip
TIn MongoDB, skip() method is used to skip the document. It is used with find() and limit() methods.
db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
db.emp.find().limit(2).skip(2);
{ "_id" : ObjectId("5f9bfedbb662c3a18997f037"), "name" : "Deepa", "age" : 24, "sal" : 20000 }
{ "_id" : ObjectId("5f9c00b0b662c3a18997f03a"), "name" : "Chaaru", "age" : 35, "dept" : { "did" : 10,
"dname" : "HR" }, "sal" : 40000 }
As you can see, the skip() method has skipped first and second documents and shows only third
and fourth document.
MongoDB -Sort
To sort documents in MongoDB, you need to use sort() method. The method accepts a
document containing a list of fields along with their sorting order. To specify sorting order 1
and -1 are used. 1 is used for ascending order while -1 is used for descending order.
db.COLLECTION_NAME.find().sort({KEY:1})
db.emp.find().limit(5).sort({"age":-1});
{ "_id" : ObjectId("5f9c00b0b662c3a18997f03a"), "name" : "Chaaru", "age" : 35, "dept" : { "did" : 10,
"dname" : "HR" }, "sal" : 40000 }
{ "_id" : ObjectId("5f9c00b0b662c3a18997f03b"), "name" : "Chaaru", "age" : 35, "dept" : { "did" : 10,
"dname" : "HR" }, "sal" : 40000 }
{ "_id" : ObjectId("5f9c0113b662c3a18997f03c"), "name" : "David", "age" : 35, "dept" : { "did" : 10,
"dname" : "Accounts" }, "address" : [ { "no" : 12, "street" : "ABC Street" }, { "no" : 22, "street" : "XYC
Street" }, { "no" : 67, "street" : "KLC Street" } ], "sal" : 40000 }
{ "_id" : ObjectId("5f9bfedbb662c3a18997f037"), "name" : "Deepa", "age" : 24, "sal" : 20000 }
{ "_id" : ObjectId("5f9bfec2b662c3a18997f036"), "name" : "Anu", "age" : 12 }
MongoDB The findOne() method
> db.emp.findOne({"First_Name" :"Fathima"});
{
"_id" : ObjectId("5f9c0d78b662c3a18997f03f"),
"First_Name" : "Fathima",
"Last_Name" : "Sheik",
"Date_Of_Birth" : "1990-02-16",
"e_mail" : "[email protected]",
"phone" : "9000054321"
}
MongoDB – Selection Relational Operator
Operation Example RDBMS Equivalent
Equality db.student.find({"name":"Bala"}) where name = 'Bala'
Less Than db.student.find({"id":{$lt:200}}) where id < 200
Less Than Equals db.student.find({"id":{$lte:200}}) where likes <= 200
Operation Example
And db.student.find({$and:[{"course":"Java"},{"age": 14}]}).pretty()
Or db.student.find({$or:[{"course":"Java"},{"age":
14}]}).pretty()
Nor db.student.find({$nor:[{"course":"Java"},{"age": 14}]}).pretty()
To query documents based on the NOT condition, you need to use $not keyword. Above is the basic
syntax of NOT −NOR,NOT
MongoDB Update
>db.emp.find()
>{ "_id" : ObjectId("5f9af629db99a0cb0f6678ce"), "name" : "uma", "age" : "96" }
>db.emp.update({'name':'uma'},{$set:{'age':'62'}})
>db.emp.find()
{ "_id" : ObjectId("5f9af629db99a0cb0f6678ce"), "name" : "uma", "age" : “62" }
MongoDB Save
db.emp.save( db.emp.find()
{ { "_id" : ObjectId("5f9aff2ddb99a0cb0f6678cf"), "name" : "Uma" }
name: “Harish", { "_id" : ObjectId("5f9b0214db99a0cb0f6678d0"), "name" : "Chaaru",
details: { "details" : { "age" : "19 years", "standard" : "BE first year" }, "Batch" : [ {
age: “18 years", "size" : "Small", "qty" : 15 }, { "size" : "Medium", "qty" : 25 } ], "category" :
standard: "BE first Year" "Computer Science" }
}, { "_id" : ObjectId("5f9b054adb99a0cb0f6678d1"), "name" : "Harish",
Batch: [ { size: "Small", qty: 15 }, "details" : { "age" : "19 years", "standard" : "BE fSec year" }, "Batch" : [ {
{ size: "Medium", qty: 25 } ], "size" : "Small", "qty" : 15 }, { "size" : "Medium", "qty" : 25 } ], "category" :
category: "Computer Science" "Computer Science" }
}
)
MongoDB Save
db.emp.save(
{ > db.emp.find()
_id : { "_id" : ObjectId("5f9aff2ddb99a0cb0f6678cf"), "name" :
ObjectId("5f9b054adb99a0cb0f6678d1"), "Uma" }
name: "Aravindan", { "_id" : ObjectId("5f9b0214db99a0cb0f6678d0"),
details: { "name" : "Chaaru", "details" : { "age" : "19 years",
age: "55 years", "standard" : "BE first year" }, "Batch" : [ { "size" : "Small",
standard: "BEr" "qty" : 15 }, { "size" : "Medium", "qty" : 25 } ], "category"
}, : "Computer Science" }
Batch: [ { size: "Small", qty: 15 }, { "_id" : ObjectId("5f9b054adb99a0cb0f6678d1"),
{ "name" : "Aravindan", "details" : { "age" : "55 years",
size: "Medium", qty: 25 } ], "standard" : "BEr" }, "Batch" : [ { "size" : "Small", "qty" :
category: "Computer Science" 15 }, { "size" : "Medium", "qty" : 25 } ], "category" :
} "Computer Science" }
)
MongoDB Delete documents
> db.emp.remove({name:"Uma"})
WriteResult({ "nRemoved" : 1 })
>
MongoDB Delete documents
If you don't specify deletion criteria, then MongoDB will delete whole documents from the
collection. This is equivalent of SQL's truncate command.
db.collection_name.remove ()
db.emp.remove({});
WriteResult({ "nRemoved" : 11 })
db.emp.find()
Thank you
Innovative Services
Passionate Employees
Delighted Customers