UNIT-3( MONGO DB)
UNIT-3( MONGO DB)
•E-commerce Applications
•Real-time Analytics
•Mobile Applications
•Gaming Applications
•Healthcare Applications
•Financial Services
MongoDB Data Types
• The BSON data format provides several different types that are
used when storing the JavaScript objects to binary form.
• It is important to understand these types because you can actually
query MongoDB to find objects that have a specific property that
has a value of a certain type.
• For example, you can look for documents in a database whose
timestamp value is a String object or query for ones whose
timestamp is a Date object.
• MongoDB assigns each of the data types an integer ID number
from 1 to 255 that is used when querying by type.
MongoDB data types and corresponding ID number
Type Number
Double 1
String 2
Object 3
Array 4
Binary data 5
Object id 7
Boolean 8
Date 9
Null 10
Regular Expression 11
JavaScript 13
MongoDB data types
• When comparing values of different BSON types, MongoDB uses the following comparison
order from lowest to highest:
• 1. Min Key (internal type)
• 2. Null
• 3. Numbers (32-bit integer, 64-bit integer, Double)
• 4. String
• 5. Object
• 6. Array
• 7. Binary Data
• 8. Object ID
• 9. Boolean
• 10. Date, Timestamp
• 11. Regular Expression
• 12. Max Key (internal type)
Planning Your Data Model
• Before you begin implementing a MongoDB database, you need to understand the nature of the data
being stored, how that data is going to get stored, and how it is going to be accessed.
• Understanding these concepts allows you to make determinations ahead of time and to structure the
data and your application for optimal performance.
• Specifically, you should ask yourself the following questions:
• What are the basic objects that my application will be using?
• What is the relationship between the different object types: one-to-one, one-to-many, or many-to-
many?
• How often will new objects be added to the database?
• How often will objects be deleted from the database?
• How often will objects be changed?
• How often will objects be accessed?
• How will objects be accessed: by ID, property values, comparisons, and so on?
How will groups of object types be accessed: by common ID, common property value, and so on?
Planning Your Data Model
1) Normalizing Data with Document References
2) Denormalizing Data with Embedded Documents.
3) Using Capped Collections
4) Understanding Atomic Write Operations
5) Considering Document Growth
6) Identifying Indexing, Sharding, and Replication Opportunities
7) Deciding on Data Life Cycles
Building the MongoDB Environment
• Installing MongoDB
• The first step in getting MongoDB implemented into your Node.js environment is installing the
MongoDB server.
• There is a version of MongoDB for each of the major platforms, including Linux, Windows, Solaris,
and OS X.
• There is also an enterprise version available for the Red Hat, SuSE, Ubuntu, and Amazon Linux
distributions.
• Before continuing, go to the MongoDB website at http://docs.mongodb.org/manual/installation/.
Follow the links and instructions to download and install MongoDB in your environment:
• As part of the installation and setup process, perform the following steps:
• 1. Download and extract the MongoDB files.
• 2. Add the <mongo_install_location>/bin to your system path.
• 3. Create a data files directory: <mongo_data_location>/data/db.
• 4. Start MongoDB using the following command from the console prompt:
mongod –dbpath <mongo_data_location>/data/db
Installing MongoDB
Installing MongoDB
Installing MongoDB
Installing MongoDB
Installing MongoDB
Accessing MongoDB from the Shell Client
• Once you have installed, configured, and started MongoDB, you can access it through the MongoDB shell.
• The MongoDB shell is an interactive shell provided with MongoDB that allows you to access, configure, and
administer MongoDB databases, users, and much more. You use the shell for everything from setting up user
accounts to creating databases to querying the contents of the database.
• To start the MongoDB shell, first make sure that mongod is running, and then run the mongod command, then
execute the mongosh command from the console prompt.
• Current Mongosh Log ID: 66f252c9808c7f3e6bc73bf7
•Connecting to:
mongodb://127.0.0.1:27017/?
directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.3.1
•Using MongoDB: 8.0.0
•Using Mongosh: 2.3.1
• For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/
• ------
•------
•test>
Understanding MongoDB Shell commands
• help <option>: Displays syntax help for MongoDB shell commands. The
option argument allows you to specify an area where you want help.
• ■ use <database>: Changes the current database handle. Database
operations are processed on the current database handle.
• ■ db.help: Displays help options for the database methods.
• ■ show <option>: Shows a list based on the option argument. The value
of option can be:
• ■ dbs: Displays a list of databases.
• ■ collections: Displays a list of collections for the current database.
• ■ profile: Displays the five most recent system.profile entries taking
more than 1 millisecond.
• ■ databases: Displays a list of all available databases.
• ■ roles: Displays a list of all roles for the current database, both built-
in and userdefined.
• ■ users: Displays a list of all users for that database.
• ■ exit: Exits the database.
MongoDB Shell vs MongoDB Server:
•MongoDB Server is responsible to store our data in database.
•By using this shell we can perform all required CRUD operations.
•C --->Create
•R --->Retrieve
•U --->Update
•D --->Delete
MongoDB Shell vs MongoDB Server:
•MongoDB Server can be either local or remote (MongoDB ATLAS) .
•To Launch/Start MongoDB Server --->mongod command
•To Launch/Start MongoDB Shell --->mongosh Command
•By default, MongoDB listens for connections from clients on port 27017 , and stores
data in the /data/db directory.
•To Check Server Version: mongod –version
• 1. admin:
admin database is used to store user authentication and authorization information .
• 2. config:
To store configuration information of mongodb server.
• 3. local:
local database can be used by admin while performing replication process.
Creation of Database and Collection
• Database won't be created at the begining and it will be created dynamically.
• Whenever we are creating collection or inserting document then database will be
• created dynamically.
• test> show dbs
• admin 0.000GB
• config 0.000GB
• local 0.000GB
• test> use MYDB1
• switched to MYDB1
• MYDB1> show dbs
• admin 0.000GB
• config 0.000GB
• local 0.000GB
How to create collection
MYDB1> db.createCollection("students")
{ ok: 1 }
• >db.employees.find().pretty()
Basic CRUD Operations
• U-->Update Operation
• db.collection.updateOne()
• db.collection.updateMany()
• db.collection.replaceOne()
If the field is available then old value will be replaced with new value.
If the field is not already available then it will be created.
The update operation document must contain atomic operators.
>db.employees.updateOne({ename: "Vinny"},{$set: {esal:10000}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Note: If anything prefixed with $ symbol, then it is predefined word in
MongoDB
Basic CRUD Operations
• D -->Delete
• db.collection.deleteOne()
• db.collection.deleteMany()
• db.employees.deleteOne({ename:"Vinny"})
MONGO DB & NODE JS
• Install MongoDB Driver
• Let us try to access a MongoDB database with Node.js.
• To download and install the official MongoDB driver, open the Command
Terminal and execute the following:
• Download and install mongodb package:
>npm install mongodb
added 12 packages, and audited 30 packages in 2s
found 0 vulnerabilitiesdb
• Connecting to MongoDB from Node.js
• Node.js can use this module to manipulate MongoDB databases:
• var mongo = require('mongodb');
MONGO DB & NODE JS
• Implement CRUD operations on the given dataset using MongoDB.
•C- CREATE
•R- READ / RETRIVE
•U- UPDATE
• D- DELETE
// Connect to database and close the database connection
// Connect to database and close the database connection
// Connect to database
client.connect()
.then(() => {
console.log('Connected Successfully!')
// Insert to database
client.db('MYDB').collection('students').insertOne({
name: 'cse1',
email: '[email protected]'
})
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))
To find one document
//to find one document
const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Insert to database
client.db('MYDB').collection('students')
.findOne({name:'cse1'})
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))
To update one document
//to update one document
const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Insert to database
client.db('MYDB').collection('students')
.updateOne({ name: 'cse1' },
{
$set:
{ email: '[email protected]' }
})
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))
To delete one document
//to delete one document
const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Insert to database
client.db('MYDB').collection('students')
.deleteOne({ name: 'cse1' })
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))
CRUD Capped Collections
• What is capped collection?
• If size exceeds or maximum number of documents reached, then oldest entry
will be deleted automatically, such type of collections are called capped
collections.
• Capped collections are fixed-size circular collections that follow the insertion order
to support high performance for create, read, and delete operations.
• By circular, it means that when the fixed size allocated to the collection is
exhausted, it will start deleting the oldest document in the collection without
providing any explicit commands.
• Capped collections restrict updates to the documents if the update results in
increased document size. Since capped collections store documents in the order of
the disk storage, it ensures that the document size does not increase the size
allocated on the disk.
• Capped collections are best for storing log information, cache data, or any other
CRUD Capped Collections
• db.createCollection("employees")- normal
• db.createCollection(name)
• db.createCollection(name,options)
• //capped
• Max 1000 documents --->1001 document
• size: 3736578 bytes only --->if space completed
• //old documents will be deleted automatically.
• db.createCollection("employees",{capped: true, size: 3736578, max: 1000})
• If capped is true means that if size exceeds or maximum number of documents
reached, then oldest entry will be deleted automatically.
CRUD Capped Collections
• 1.db.createCollection("employees") --->Normal Collection
• 2. db.createCollection("employees",{capped: true}) --->Invalid
• "errmsg" : "the 'size' field is required when 'capped' is true",
• 3. db.createCollection("employees",{capped: true, size: 365675})--->valid
• 4. db.createCollection("employees",{size: 365675}) --->invalid
• "errmsg" : "the 'capped' field needs to be true when either
the 'size' or 'max' fields are present“
• 5. db.createCollection("employees",{capped: true, size: 365675, max: 1000})---
>valid
• db.createCollection("employees",{capped: true, size: 365675, max: 1})