You are on page 1of 56

Tintu Alphonsa Thomas | Assistant Professor, CSE |

Amal Jyothi College of Engineering,Kanjirappally


mongoDB –Introduction
 mongoDB is an open-source document database that provides high
performance, high availability, and automatic scaling.
 mongoDB is a Document-Oriented Database.
 It is an open source product, developed and supported by a
company named 10gen.
 “mongoDB is a scalable, open source, high performance,
document-oriented database." 
History of MongoDB
 MongoDB was developed by a NewYork based organization named
10gen which is now known as MongoDB Inc.
 It was initially developed as a PAAS (Platform as a Service).
 Later in 2009, it is introduced in the market as an open source
database server that was maintained and supported by MongoDB Inc.
 The first ready production of MongoDB has been considered from
version 1.4 which was released in March 2010.
The primary purpose of building MongoDB is:
• Scalability
• Performance
• High Availability
• Scaling from single server deployments to large, complex multi-site
architectures.
Key points of MongoDB
• Develop Faster
• Deploy Easier
Document-Oriented Database
 MongoDB is a document oriented database.
 It is a key feature of MongoDB.
 It offers a document oriented storage. It is very simple you can
program it easily.
 MongoDB stores data as documents, so it is known as document-
oriented database.
 MongoDB is a document database, which means it stores data in
JSON-like documents. 
MONGO DB vs RDBMS
[
{
“First-name” : “Joe”,
“Last-name” : “Thomas”, First-name Last-name email
“email” : “joethomas@abc.in”
Joe Thomas joethomas@abc.in
},

{ Jia Jacob jiajacob@abc.in


“First-name” : “Jia”,
“Last-name” : “Thomas”,
“email” : “jiathomas@abc.in”
}
]
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
Double Double datatype stores floating point values.
Arrays This datatype is used to store a list or multiple values into a single key.

Object Object datatype is used for embedded documents.

Null It is used to store null values.


Symbol It is generally used for languages that use a specific type.

Date This datatype stores the current date or time in unix time format. It makes you possible to specify your own date time by
creating object of date and pass the value of date, month, year into it.
NoSQL Databases
 NoSQL Database is used to refer a non-SQL or non relational
database.
 It provides a mechanism for storage and retrieval of data other than
tabular relations model used in relational databases.
 NoSQL database doesn't use tables for storing data.
 It is generally used to store big data and real-time web applications.
MongoDB Advantages
• mongoDB is schema less.
• It is a document database in which one collection holds different
documents.
• There may be difference between number of fields, content and
size of the document from one to other.
• Structure of a single object is clear in MongoDB.
• There are no complex joins in MongoDB.
• It uses internal memory for storing working sets and this is the
reason of its fast access.
 MongoDB Atlas provides an easy way to host and manage your data
in the cloud.
 Creating an Atlas cluster, connecting to it, inserting data, and
querying data
 https://www.mongodb.com/cloud/atlas/register
Get Started with Atlas
1. Click Sign up with Google.
2. Enter one of the following identifiers for your Google account:
 Your Gmail or Google Apps email address
 Phone number associated with your Google account
3. Click Next.
4. Enter the password for your Google account.
5. Click Next.
6. Review and select the checkbox to accept the Terms of Service and
the Privacy Policy.
7. Click Submit.
Create an Atlas Organization and Project
 Create an Atlas organization and then create a project in this
organization.
 You will deploy your first cluster in this project.
 With your Atlas account, open the organization and its project, and
then proceed to Deploy a Free Tier Cluster.
 https://docs.atlas.mongodb.com/tutorial/deploy-free-tier-cluster/
Deploy a Free Tier Cluster
 Atlas Free Tier clusters provide a small-scale development
environment to host your data.
 Free Tier clusters never expire, and provide access to a subset of
Atlas features and functionality.
 Paid clusters provide full access to Atlas features, configuration
options, and operational capabilities.
 You can deploy only one Free Tier cluster per Atlas project.
Procedure
Log into Atlas
 Once you log in, open your organization and find your project. 
 Atlas prompts you to build your first cluster
 Build a Cluster
Select Starter Clusters and click Create a Cluster.
Select your preferred Cloud Provider & Region
Select M0 Sandbox for cluster tier
 Selecting M0 automatically locks the remaining configuration
options.
 If you cannot select the M0 cluster tier, return to the previous step
and select a Cloud Provider & Region that supports M0 Free Tier
clusters.
Enter a name for your cluster in the Cluster Name field
 You can enter any name for your cluster.
Click Create Cluster to deploy the cluster
 Once you deploy your cluster, it can take up to 10 minutes for your
cluster to provision and become ready to use.
Add Your Connection IP Address to IP Access List
 An IP is a unique numeric identifier for a device connecting to a
network.
 In Atlas, you can only connect to a cluster from a trusted IP address.
Within Atlas, you can create a list of trusted IP addresses, referred to
as a IP access list, that can be used to connect to your cluster and
access your data.
 You must add your IP address to the IP access list before you can
connect to your cluster. To add your IP address to the IP access list
 Click Connect
 Click Add Your Current IP Address.

 The menu expands to show the Add a connection IP address modal.


 Click Add IP Address
Create a Database User for Your Cluster
 You must create a database user to access your cluster.
 For security purposes, Atlas requires clients to authenticate as
MongoDB database users to access clusters.
 Database users are separate from Atlas users:
• Database users can access databases hosted in Atlas.
• Atlas users can log in to Atlas but do not have access to MongoDB
databases.
To add a database user to your cluster:

 Click Connect
 In the Clusters view, click Connect for the cluster to which you
want to connect.
 Set the new user's Username and Password
 You'll use this username and password combination to grant a user
access to databases and collections in your cluster in  Atlas project.
 Click Create Database User
Connect to Your Atlas Cluster
In Atlas, you can connect to your cluster using the following
connection methods:
•Connect with the mongo shell to interact with your cluster using the
Javascript interface of the mongo Shell.
•Connect your application to your cluster using the Node.js driver, or
the PyMongo driver.
•Connect to your cluster using MongoDB Compass to explore, modify,
and visualize your data with Compass.
Connect to Your Cluster
 Download and Install Utility
 Download the installer from the MongoDB Community Downloads.
 Add the mongo shell to your system path.
 To run the mongo shell from your terminal, you will need to add the
shell to your system path.
Add the bin directory to your command path.
1.Select Control Panel.
2.Click System and Security, then System, then Advanced System
Settings.
3.Click Environment Variables.
4.Select Path and click Edit.
5.Add the bin directory where the installer placed your MongoDB
executables and click OK.
You should now be able to run the mongo shell using your terminal.
Test your mongo shell installation
 To see if you have correctly added the mongo shell to your system
path, run the following command in your terminal:
mongo --version

You should see an output similar to the following:


MongoDB shell version v4.0.7
git version: 7c13a75b928ace3f65c9553352689dc0a6d0ca83
allocator: system
modules: none
build environment:
distarch: x86_64
target_arch: x86_64
Now that you have installed the mongo shell, you can use the shell
to connect to your Atlas cluster.
 In the Clusters view, click Connect for the cluster to which you
want to connect.
 Click Choose a connection method.
 Click Connect with the mongo shell.
 Click I have the mongo shell installed and select your mongo shell
version from the drop-down.
 Copy the provided connection string to your clipboard.
 This is a unique connection string specific to your Atlas cluster. 
 Atlas replaces the username of the connection string with the
username of the database user you created earlier in this procedure.
 Paste and run your connection string in your terminal.
 When prompted, enter your database user's password
 You should now be connected to your Atlas cluster within the mongo
shell.
 Your terminal should display something similar to the following:
MongoDB Enterprise GettingStarted-shard-0:PRIMARY>
MongoDB CRUD Operations
 CRUD Operations include :

 Create Operations

 Read operations

 Update Operations

 Delete Operations
1. Create Operations
 Insert and View Data in Your Cluster Using the Shell
.
 Switch to a new database called gettingStarted
 In the mongo, run the following command:

use gettingStarted

 This command creates a new database called gettingStarted and


points your mongo shell environment to that database.
Creating Collections
.
 In the mongo, run the following command:

> db.createCollection("people")

 This command creates a collection in gettingStarted called people


points your mongo shell environment to that database.
{ "ok" : 1 }
 Insert a document into your database
 In mongo shell, run the following command to insert a document
into your new database- gettingStarted.
db.people.insert({
name: { first: "Alan", last: "Turing" },
birth: new Date('Jun 23, 1912'),
death: new Date('Jun 07, 1954'),
contribs: [ "Turing machine", "Turing test", "Turingery" ],
views : NumberLong(1250000)
})

This command creates a new collection in your gettingStarted


 This command creates a new collection in your gettingStarted
database called people and inserts one document into that collection.
 You should see the following output, confirming that you have
successfully inserted a document into your collection:

WriteResult({ "nInserted" : 1 })
Inserting Multiple Documents
.
 There are two other ways for inserting documents other than insert()
db.people.insertOne({name:'name1’})

db.people.insertMany([{name:'name3'},{name:'name4'}])

 This commands create documents in gettingStarted. insertMany()


lets you to create multiple documents inside the argument.
2. Read Operations
View Data Using the Shell
 The following command displays all the documents inside the collection.
pretty() displays in a attractive format.

db.people.find().pretty()

 When you run this command, you should see the following output:
 You may see a different value for ObjectId, because it is a system-generated
value.
db.people.find().pretty()
{
"_id" : ObjectId("60d5f084be3d27f0037e3028"),
"name" : {
"first" : "Alan",
"last" : "Turing"
},
"birth" : ISODate("1912-06-22T18:30:00Z"),
"death" : ISODate("1954-06-06T18:30:00Z"),
"contribs" : [
"Turing machine",
"Turing test",
"Turingery"
],
"views" : NumberLong(1250000)
}
{ "_id" : ObjectId("60d5fea0be3d27f0037e3029"), "name" : "name1" }
{ "_id" : ObjectId("60d60a7ebe3d27f0037e302a"), "name" : "name3" }
{ "_id" : ObjectId("60d60a7ebe3d27f0037e302b"), "name" : "name4" }
Specify the no. of results to be displayed
 The limit() function in MongoDB is used to specify the maximum number of
results to be returned. 

db.people.find().limit().pretty()

 When you run this command, you should see the following output:
 You may see a different value for ObjectId, because it is a system-generated
value.
{
"_id" : ObjectId("60d5f084be3d27f0037e3028"),
"name" : {
"first" : "Alan",
"last" : "Turing"
},
"birth" : ISODate("1912-06-22T18:30:00Z"),
"death" : ISODate("1954-06-06T18:30:00Z"),
"contribs" : [
"Turing machine",
"Turing test",
"Turingery"
],
"views" : NumberLong(1250000)
}
{ "_id" : ObjectId("60d5fea0be3d27f0037e3029"), "name" : "name1" }
Fetch documents with conditions
 We can add conditions in the find()

db.people.find({ 'name.first' : 'Alan' }).pretty()

 When you run this command, you should


{ see the following output:
"_id" : ObjectId("60d5f084be3d27f0037e3028"),
"name" : {
"first" : "Alan",
"last" : "Turing"
},
"birth" : ISODate("1912-06-22T18:30:00Z"),
"death" : ISODate("1954-06-06T18:30:00Z"),
"contribs" : [
"Turing machine",
"Turing test",
"Turingery"
],
"views" : NumberLong(1250000)
Sorting the documents
 The sort() function in MongoDB is used to sort a field according to the sorting
order.
 sorting order: 1(ascending), -1(descending)

db.people.find().sort({name:1}).pretty()

 When you run this command, you should see the following output:
{ "_id" : ObjectId("60d5fea0be3d27f0037e3029"), "name" : "name1" }
{ "_id" : ObjectId("60d60a7ebe3d27f0037e302a"), "name" : "name3" }
{ "_id" : ObjectId("60d60a7ebe3d27f0037e302b"), "name" : "name4" }
{
"_id" : ObjectId("60d5f084be3d27f0037e3028"),
"name" : {
"first" : "Alan",
"last" : "Turing"
},
"birth" : ISODate("1912-06-22T18:30:00Z"),
"death" : ISODate("1954-06-06T18:30:00Z"),
"contribs" : [
"Turing machine",
"Turing test",
"Turingery"
],
"views" : NumberLong(1250000)
}
selects the documents where the value of the field is not equal to the specified value. T

Not Equal to Condition


 $ne selects the documents where the value of the fields which are not equal
to specified value.
db.people.find({ 'name.last' : { $ne : 'Turing'} }).pretty()

 When you run this command, you should see the following output:

{ "_id" : ObjectId("60d5fea0be3d27f0037e3029"), "name" : "name1" }


{ "_id" : ObjectId("60d60a7ebe3d27f0037e302a"), "name" : "name3" }
{ "_id" : ObjectId("60d60a7ebe3d27f0037e302b"), "name" : "name4" }
selects the documents where the value of the field is not equal to the specified value. T

OR Condition
 $or operator performs a logical OR operation on an array of two or more and
selects the documents that satisfy at least one of the expressions.

db.people.find({ $or: [{'name.first':'Turing'},{name:'name4'}] }).pretty()

 When you run this command, you should see the following output:

{ "_id" : ObjectId("60d60a7ebe3d27f0037e302b"), "name" : "name4" }

 The second condition returns true and that document is displayed.


selects the documents where the value of the field is not equal to the specified value. T

count()
 count() returns the number of documents in a collection.

db.people.find({ name: 'name3’ }).count()

 When you run this command, you should see the following output: 1
selects the documents where the value of the field is not equal to the specified value. T

findOne()
 findOne() returns the first document in a collection.

db.people.findOne()

 When you run this command, you should


{ see the following output:
"_id" : ObjectId("60d5f084be3d27f0037e3028"),
"name" : {
"first" : "Alan",
"last" : "Turing"
},
"birth" : ISODate("1912-06-22T18:30:00Z"),
"death" : ISODate("1954-06-06T18:30:00Z"),
"contribs" : [
"Turing machine",
"Turing test",
"Turingery"
],
"views" : NumberLong(1250000)
}
selects the documents where the value of the field is not equal to the specified value. T

selecting fields to display


 select the fields inside the 2nd argument of find()

db.people.find( { },{ name: 1, _id:0 } )

 When you run this command, you should see the following output:

{ "name" : { "first" : "Alan", "last" : "Turing" } }


{ "name" : "name1" }
{ "name" : "name3" }
{ "name" : "name4" }
selects the documents where the value of the field is not equal to the specified value. T

count()
 count() returns the number of documents in a collection.

db.people.find({ name: 'name3’ }).count()

 When you run this command, you should see the following output: 1
3. Update Operations
replace an existing value with new value
 modify specific fields of an existing document or documents or replace an existing
document entirely, depending on the update parameter.

db.people.update({name:'name4'},{name: 'name 4'})


 When you run this command, you should see the following output:
{ "name" : { "first" : "Alan", "last" : "Turing" } }
{ "name" : "name1" }
{ "name" : "name3" }
{ "name" : "name 4" }

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })


update selected fields only
 modify specific fields of an existing document or documents or replace an existing

document entirely, depending on the condition.

 the first {} represents the condition

db.people.find.update({'name.first' : 'Alan'},{$set: {views:1000} })

 $set:{} assigns the value which needs to be updated


 When you run this command, you should see the following
output of the first document :
{
"_id" : ObjectId("60d5f084be3d27f0037e3028"),
"name" : {
"first" : "Alan",
"last" : "Turing"
},
"birth" : ISODate("1912-06-22T18:30:00Z"),
"death" : ISODate("1954-06-06T18:30:00Z"),
"contribs" : [
"Turing machine",
"Turing test",
"Turingery"
],
"views" : 1000
}
rename property
 rename property operator updates the name of a field with the provided value
db.people.find.update({'name.first' : 'Alan'},{$set: {views:1000} })
 output of the first document looks like:
{
"_id" : ObjectId("60d5f084be3d27f0037e3028"),
"name" : {
"first" : "Alan",
"last" : "Turing"
},
"birth" : ISODate("1912-06-22T18:30:00Z"),
"death" : ISODate("1954-06-06T18:30:00Z"),
"contribs" : [
"Turing machine",
"Turing test",
"Turingery"
],
"likes" : 1000
}
3. Delete Operations
removes the collection

 remove() removes the document containing the property name and the
value associated property mentioned in the collection
db.people.remove({'name.last:'Turing'})

{ "_id" : ObjectId("60d5fea0be3d27f0037e3029"), "name" : "name1" }


{ "_id" : ObjectId("60d60a7ebe3d27f0037e302a"), "name" : "name3" }
{ "_id" : ObjectId("60d60a7ebe3d27f0037e302b"), "name" : "name 4" }

WriteResult({ "nRemoved" : 1 })
Conclusion
 You've just set up an Atlas cluster to host your data, and used the
mongo shell to write and read data to and from your cluster.

 Learned about the CRUD operations in a MongoDB

You might also like