0% found this document useful (0 votes)
19 views23 pages

Mongo DB

This document serves as a lab manual for MongoDB, detailing its features as a document-oriented NoSQL database, including its schema-free nature, BSON data format, sharding, and map-reduce capabilities. It provides commands for database operations such as creating, deleting, and manipulating collections, as well as querying data using methods like find() and update(). Additionally, it compares MongoDB terminology with traditional RDBMS concepts and includes examples of various MongoDB operations.

Uploaded by

shosho108oo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views23 pages

Mongo DB

This document serves as a lab manual for MongoDB, detailing its features as a document-oriented NoSQL database, including its schema-free nature, BSON data format, sharding, and map-reduce capabilities. It provides commands for database operations such as creating, deleting, and manipulating collections, as well as querying data using methods like find() and update(). Additionally, it compares MongoDB terminology with traditional RDBMS concepts and includes examples of various MongoDB operations.

Uploaded by

shosho108oo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

2/22/2018

mongoDB
Lab Manual

mongoDB
• Document-oriented NoSQL database.
• Schema-free.
• Based on Binary JSON; BSON.
• Organized in Group of Documents
• Collections
• Informal name spacing
• Auto-Sharding in order to scale horizontally.
• Simple query language. Rich, document-based
queries.
• Map/Reduce support.
• Open Source (GNU AGPL v3.0.)
2

1
2/22/2018

JSON; BSON
• JSON (JavaScript Object Notation) is a lightweight data-
interchange format.
• BSON /ˈbiːsən/ is a computer data interchange format
used mainly as a data storage and network transfer format
in the MongoDB database.

• It is a binary form for representing simple data structures,


associative arrays (documents in MongoDB), and various
data types of specific interest to MongoDB.

• BSON extends the JSON model to provide additional data


types and to be efficient for encoding and decoding within
different languages.

Sharding
• Sharding is a type of database
partitioning that separates very large
databases the into smaller, faster, more
easily managed parts called data shards. The
word shard means a small part of a whole.
• Tables are divided and distributed into
multiple servers.
• The total number of rows in each table in
each database is reduced.
• Improves search performance.
4

2
2/22/2018

Map-reduce
• Map-reduce is a data processing paradigm
for condensing large volumes of data into
useful aggregated results.
• For map-reduce operations, MongoDB
provides the mapReduce database
command.

Relationship of RDBMS
terminology with MongoDB
RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
column Field
Table Join Embedded Documents
Primary Key (Default key _id provided
Primary Key by mongodb itself)

Database Server and Client


Mysqld/Oracle mongod
mysql/sqlplus mongo

3
2/22/2018

MongoDB Blocks

Creating the Database


The use Command is used to create database.
The command will create a new database if it
doesn't exist, otherwise it will return the existing
database.

Syntax : use DATABASE


Ex: use College

4
2/22/2018

Deleting the Database


The db.dropDatabase() Command is
used to drop an existing database.

Syntax : db.dropDatabase()
Ex:
>use College
switched to db College
>db.dropDatabase()
>{ "dropped" : "College", "ok" : 1 }
>
9

The createCollection() Method


It is used to Create a Collection

Syntax :
db.createCollection(name, options)

Ex:
>db.createCollection("Student")

10

5
2/22/2018

The drop() Method


The db.collection.drop() is used to drop
a collection from the database.

Syntax :
db.COLLECTION_NAME.drop()

Ex:
>db.Student.drop()

11

Miscellaneous Commands
>db To check your currently selected
database.

>show dbs To Display all the Databases.

>show collections To Display all the


collections under the current Database

12

6
2/22/2018

Data Types
Data Type Description
To store the data. String in MongoDB must be
String UTF-8 valid.
To store a numerical value. Integer can be 32
Integer bit or 64 bit depending upon your server.
Boolean To store a Boolean (true/ false) value.
Double To store floating point values.
Min/Max To compare a value against the lowest and
Keys highest BSON elements.
To store arrays or list or multiple values into
Arrays one key.
This can be handy for recording when a
Timestamp document has been modified or added.
This datatype is used for embedded
Object documents.
13

Data Types (Cont..)


Data Type Description
Null This type is used to store a Null value.
This datatype is used identically to a string; however, it's
generally reserved for languages that use a specific symbol
Symbol type.
This datatype is used to store the current date or time in
UNIX time format. You can specify your own date time by
creating object of Date and passing day, month, year into
Date it.
Object ID This datatype is used to store the document’s ID.

Binary data This datatype is used to store binary data.


This datatype is used to store JavaScript code into the
Code document.
Regular
expression This datatype is used to store regular expression.
14

7
2/22/2018

MongoDB Operations

users

15

The insert() Method (Cont..)


To insert data into MongoDB collection,
you need to use MongoDB's insert() or
save()method. .

Syntax of insert():
>db.COLLECTION_NAME.insert(document)

16

8
2/22/2018

The insert() Method


Insert
SQL

MongoDB

17

The insert() Method (Cont..)

18

9
2/22/2018

The insert() Method (Cont..)


Ex 1:
>db.Student.insert({sid:"1001",
name:"waleed", address:"muscat"})
Ex 2:
>db.Student.insert({sid:"1002",
name:"Ahmed", age:26,
address:"Shinas", courses:["database",
"networking","maths"]})

19

The insert() Method (Cont..)


Ex 3:
>db.Student.insert
(
{
sid:"1003", name:"Faisal", age:29, phone:
"91919292", address:"Ibra", courses:["WT",
"networking","maths"]
},
{
sid:"1004", name:"Rashid", age:21, phone:
"95219254", address:"Musanna", courses:["Appled
DB", "networking","Intro to DB"]
}
)
20

10
2/22/2018

The insert() Method (Cont..)


Ex 4:
>db.Student.insert
(
{
sid:"1005", name:"Osama", age:21, phone:
"97969594", address:"Ibri", courses:["WT", "Intro to
DB","maths"], dept: "Business"
},
{
sid:"1006", name:"Asim", age:24, dept: "IT", phone:
"92215253", address:"Muscat", courses:["Appled
DB", "WT","Intro to DB"]
}
)
21

The find() Method


• To query data from MongoDB collection,
you need to use MongoDB's find()method.
• This method will display all the documents
in a non-structured way.
Syntax of find():
>db.COLLECTION_NAME.find()

Ex 1: >db.Student.find()
Ex 2: >db.Student.find({sid:"1004"})

22

11
2/22/2018

The pretty() Method


• To display the results in a formatted way,
you can use pretty() method.
Syntax of pretty():
>db.COLLECTION.find().pretty()
Ex:
 db.Student.find({id:"1003"}).pretty()
 db.Student.find({name:"Faisal"}).pretty()

Apart from find() method, there is findOne() method,


that returns only one document.

23

Array elements
• The following syntax allows us to apply a
condition on a required element of an
array.

Syntax:
db.COLLECTION.find( { “ARRAY-NAME.
INDEX-NUMBER": “VALUE" } )
Ex :
db.Student.find( { "courses.0": "WT" } )

24

12
2/22/2018

RDBMS Where Clause Equivalents in MongoDB

RDBMS
Operation Syntax Example
Equivalent
where
Equality {<key>:<value>} db.Student.find({"address":"Muscat"}).pretty()
address="Muscat"

Less than {<key>:{$lt:<value >}} db.Student.find({"age":{$lt:25}}).pretty() where age<25

Less than or
{<key>:{$lte:<value >}} db.Student.find({"age":{$lte:25}}).pretty() where age<=25
Equal

Greater than {<key>:{$gt:<value >}} db.Student.find({"age":{$gt:25}}).pretty() where age>25

Greater than
{<key>:{$gte:<value >}} db.Student.find({"age":{$gte:25}}).pretty() where age>=25
or Equal

Not Equal {<key>:{$ne:<value >}} db.Student.find({"age":{$ne:25}}).pretty() where age!=25

25

MongoDB Operations (Cont..)

Find the users of age greater than 18 and sort by age.

26

13
2/22/2018

MongoDB Operations (Cont..)

Update the users of age greater than 18 by setting the status field to A.

SQL

MongoDB

27

MongoDB Operations (Cont..)

Delete the users with status equal to D.

SQL

MongoDB

28

14
2/22/2018

MongoDB Operations (Cont..)


SQL SELECT Statements MongoDB find() Statements
SELECT * FROM users db.users.find()
SELECT id, user_id, status FROM users db.users.find({ },{ user_id: 1, status: 1 })
SELECT user_id, status FROM users db.users.find({ },{ user_id: 1, status: 1, _id: 0)
SELECT * FROM users WHERE status =
db.users.find({ status: "A" })
"A"
SELECT user_id, status FROM users db.users.find({ status: "A" },{ user_id: 1, status: 1,
WHERE status = "A" _id: 0)
SELECT * FROM users WHERE status !=
db.users.find({ status: { $ne: "A" } })
"A"
SELECT * FROM users WHERE status =
db.users.find({ status: "A",age: 50 })
"A" AND age = 50
SELECT * FROM users WHERE status =
db.users.find({ $or: [ { status: "A" } ,{ age: 50 } ] })
"A" OR age = 50
SELECT * FROM users WHERE age > 25 db.users.find({ age: { $gt: 25 } })
SELECT * FROM users WHERE age < 25 db.users.find({ age: { $lt: 25 } })
SELECT * FROM users WHERE age > 25
db.users.find({ age: { $gt: 25, $lte: 50 } })
AND age <= 50
SELECT * FROM users WHERE user_id like
db.users.find( { user_id: /bc/ } )
"%bc%" 100
29

MongoDB Operations (Cont..)

SQL Update Statements MongoDB update() Statements

UPDATE users SET status = "C" db.users.update( { age: { $gt: 25 } }, { $set: {


WHERE age > 25 status: "C" } }, { multi: true })

UPDATE users SET age = age + 3 db.users.update( { status: "A" } , { $inc: { age: 3
WHERE status = "A" } }, { multi: true })

SQL Delete Statements MongoDB remove() Statements


DELETE FROM users WHERE status =
db.users.remove( { status: "D" } )
"D"
DELETE FROM users db.users.remove({})

30

15
2/22/2018

AND in MongoDB
• In the find() method, if you pass multiple
keys by separating them by ',' then
MongoDB treats it as AND condition.

Syntax:
>db.mycol.find({key1:value1,
key2:value2}).pretty()
Ex :
>db.Student.find({age:29,address:"Ibra"}).pretty()

31

OR in MongoDB
• To query documents based on the OR
condition, you need to use $or keyword.

Syntax:
>db.mycol.find(
{
$or: [ {key1: value1}, {key2:value2} ]
} ).pretty()
Ex :
>db.Student.find({$or:[{age:29},{address:"Ibra"}]}).pretty()

32

16
2/22/2018

Using AND and OR Together


• SQL
where age>25 AND (address = 'Ibra' OR
address = 'Muscat')
• mongoDB
Ex :
>db.Student.find({age: {$gt:25},
$or: [{address: "Ibra"},
{"address": "Muscat"}]}).pretty()

33

MongoDB - Update Document

• MongoDB's update() and save()


methods are used to update
document into a collection.

34

17
2/22/2018

MongoDB Update() Method


• The update() method updates the values
in the existing document.
Syntax:
>db.COLLECTION_NAME.update(SEL
ECTIOIN_CRITERIA,
UPDATED_DATA)
Ex :
>db.Student.update({address:"Ibri"
},{$set:{address:"Musanna"}})

35

MongoDB Update() Method (Cont..)


• By default, MongoDB will update only a
single document. To update multiple
documents, you need to set a parameter
'multi' to true.

Ex:
>db.Student.update({address:"Ibri"},{$set:{ad
dress:"Musanna"}} ,{multi:true})

36

18
2/22/2018

MongoDB Save() Method


• The save() method replaces the existing
document with the new document passed
in the save() method.
Syntax:
>db.COLLECTION_NAME.save({_id:ObjectId
(),NEW_DATA})
Ex :
>db.Student.save({"_id" :
ObjectId("582a8fd44ce8cb2ce16a724d"), sid:"1001",
name:"Waleed", address:"Muscat",
phone:"96569856"})
37

The remove() Method


• MongoDB's remove() method is used to
remove a document from the collection.
remove() method accepts two
parameters. One is deletion criteria and
second is justOne flag.
• deletion criteria: (Optional) deletion
criteria according to documents will be
removed.
• justOne: (Optional) if set to true or 1,
then remove only one document.
38

19
2/22/2018

The remove() Method (Cont..)


Syntax:
>db.COLLECTION_NAME.remove(DELLETI
ON_CRITTERIA)

Ex :
>db.Student.remove({"Address":"Ibra"})

39

The remove() Method (Cont..)


• Remove Only One: If there are multiple
records and you want to delete only the
first record, then set justOne parameter
in remove() method.

Syntax:
>db.COLLECTION_NAME.remove(DELETIO
N_CRITERIA,1)

40

20
2/22/2018

The remove() Method (Cont..)


• Remove All 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.

Syntax:
>db.COLLECTION-NAME.remove()

41

MongoDB - Projection
• Projection can allows us to filter the
Collection Vertically.
• You can select the required columns of a
collection using the second optional
parameter [1 or 0]of find() method.
• 1 is used to show the field.
• 0 is used to hide the fields

Syntax:
>db.COLLECTION_NAME.find({},{KEY:1})

42

21
2/22/2018

MongoDB – Projection (Cont..)


• Please note _id field is always displayed
while executing find() method, if you don't
want this field, then you need to set it as 0.
Ex 1:
>db.Student.find({},{name:1,_id:0})

Ex 2:
>db.Student.find({address:"Musanna"},{name:
1, address:1, _id:0})

43

MongoDB – Projection (Cont..)


• To display excluding the _id and address
columns.
Ex 1:
>db.Student.find({},{_id:0, address:0})

44

22
2/22/2018

The sort() Method


• To sort documents in MongoDB, you need
to use sort() method.
• To specify sorting order 1 and -1 are used.
• 1 is used for ascending order
• -1 is used for descending order.

Syntax:
>db.COLLECTION_NAME.find().sort({KEY:1})
Ex :
> db.Student.find({},{name:1,_id:0}).sort({name:1})

45

MongoDB - Indexing
The ensureIndex() Method: To create an index
you need to use ensureIndex() method of
MongoDB.
Here key is the name of the file on which you want
to create index and 1 is for ascending order. To
create index in descending order you need to use -1.
Syntax:
>db.COLLECTION_NAME.ensureIndex({KEY:1})
Ex 1: >db.Student. ensureIndex({name:1})
Ex 2: >db.Student. ensureIndex({name:1, address:-1})

46

23

You might also like