SlideShare a Scribd company logo
DOCUMENT BASED DATABASE
(MongoDB)
INTRODUCTION
• MongoDB is a schema-free document database written in C++ and
developed in an open-source project which is mainly driven by the
company 10gen Inc that also offers professional services around
MongoDB.
• the main goal of MongoDB is to close the gap between the fast and
highly scalable key-/value-stores and feature-rich traditional RDBMSs
relational database management systems.
• A database contains one or more collections consisting of documents.
• MongoDB is schema-free the documents within a collection may be
heterogeneous although the
• Once the first document is inserted into a database, a collection is
created automatically and the inserted document is added to this
collection.
It store data (which is in BSON – “Binary Serialized Document Notation” ) format
Advantage
Documents are independent units which makes performance better
(related data is read contiguously off disk) and makes it easier to
distribute data across multiple servers.
Application logic is easier to write. You don’t have to translate between
objects in your application and SQL queries, you can just turn the object model
directly into a document
Non-relational databases are highly scalable than the relational databases.
Non-relational databases process data faster than the relational databases
because they do not use ACID properties.
Non-relational databases are very flexible than the relational databases
because they are schemaless.
Disadvantage
Non-relational databases are less reliable than the relational databases
because they compromise reliability for performance.
Non-relational databases alsocompromise consistency for performance
In many non-relational databases security is lesser than relational databases
which is a major concern.
Like Mongodb and Cassandra both databases have lack of encryption for data
files, they have very weak authentication system, and very simple
authorization .
INSTALLATION
Step 1:- Download the latest production release of
MongoDB
Step 2:- Extract the downloaded archive.
• In Windows Explorer, find the MongoDB download file, typically in the
default Downloads directory.
• Extract the archive to C: by right clicking on the archive and selecting
Extract All and
Step 3:- Move the MongoDB directory to another
location.
• cd 
• move C:mongodb-win32-* C:mongodb
INSTALLATION(Cont…)
Step 4:- Set Up the Data Directory
Step 5:- Start MongoDB
The default location for the MongoDB data directory is C:datadb.
Create this folder using the Command Prompt. Go to the C: directory
and issue the following command sequence:
md data
md datadb
You can specify an alternate path for data files using the
C:mongodbbinmongod.exe --dbpath d:testmongodbdata
C:mongodbbinmongod.exe
This will start the main MongoDB database process. The waiting for
connections message in the console
output indicates that the mongod.exe process is running successfully.
INSTALLATION(Cont…)
Step 6:- Connect to MongoDB
Connect to MongoDB using the mongo.exe shell.
C:mongodbbinmongo.exe
The mongo.exe shell will connect to mongod.exe running on the
localhost interface and port 27017 by default.
BASIC OPERATIONS
Oper 1:- Related to Database
After starting the mongo shell your session will use the test database by
default.
• To show the name of current database -> DB
• To display list of database -> show dbs
• Switch to a new database named mydb or create new database -> use
mydb
NOTE:MongoDB will not permanently create a database until you
insert data into that database.
BASIC OPERATIONS(Cont…)
Oper 2:- Create a Collection and Insert Documents
• MongoDB uses dynamic schemas , you also need not specify the
structure of your documents before inserting them into the
collection.
• Insert documents in testDb collection
db.testDb.insert({x: 20})
db.testDb.insert({x: 25 , name: “mongo”})
• When you insert the first document, the mongod will create both a
mydb database and the testData collection.
• All MongoDB documents must have an _id field with a unique
value. These operations do not explicitly specify a value for the _id
field, so mongo creates a unique ObjectId value for the field before
inserting it into the collection.
BASIC OPERATIONS(Cont…)
• To show list of collections in current database -> show collections
• To show list of documents in collection -> db.testDb.find()
• Query for Specific Documents -> db.testDb.find({x: 18})
• Limit the Number of Documents in the Result Set ->
db.testDb.find().limit(3)
Oper 3:- Update an existing document
• In MongoDB, db.collection.update() and the db.collection.save() methods
perform update operations.
BASIC OPERATIONS(Cont…)
•By default, the db.collection.update() method updates a single document.
However, with the multi option, update() can update all documents in a collection
that match a query.
db.inventory.update(
{ type: "book", item : "journal" },
{ $set : { qty: 10 } },
{ upsert : true }
)
•Call the update() method with the upsert flag to create a new document if no
document matches the update’s query criteria.
BASIC OPERATIONS(Cont…)
By default, db.collection.remove() method removes all documents that match its
query. However, the method can accept a flag to limit the delete operation to a
single document.
Oper 4:- Delete an existing document
In MongoDB, db.collection.remove() method performs delete operations.
Oper 5:- Fetching documents from collections
BASIC OPERATIONS(Cont…)
BASIC OPERATIONS(Cont…)
Specifying an equality condition –> db.inventory.find( { type: "snacks" } )
Specify Conditions Using Query Operators -> db.inventory.find( { type: {
$in: [ 'food', 'snacks' ] } } )
Specify AND Conditions -> db.inventory.find( { type: 'food', price: { $lt:
9.95 } } )
Specify OR Conditions -> db.inventory.find({ $or: [{ qty: { $gt: 100 } },
{ price: { $lt: 9.95 } }]})
BASIC OPERATIONS(Cont…)
BASIC TERMS
• Queries in MongoDB return all fields in all matching documents by default. To
limit the amount of data that MongoDB sends to applications, include a projection
in the queries.
1:- Projection
Exclude One Field From a Result Set
db.records.find( { "user_id": { $lt: 42} }, { history: 0} )
NOTE : you cannot mix exclusive and inclusive projections , Except for excluding
the _id field in inclusive projections.
Return Two Fields and Exclude _id
db.records.find( { "user_id": { $lt: 42} }, { "_id": 0, "name": 1 , "email": 1 } )
2:- Cursors
In the mongo shell, the primary method for the read operation is the
db.collection.find() method. This method queries a collection and returns a
cursor to the returning documents.
SQL to MongoDB Mapping Chart
SQL Terms/Concepts MongoDB Terms/Concepts
database database
table collection
row document or BSON document
column field
index index
table joins embedded documents and linking
primary key
Specify any unique column or column
combination as primary key.
primary key
In MongoDB, the primary key is
automatically set to the_id field.
SQL to MongoDB Mapping Chart
SQL Schema Statements MongoDB Schema Statements
CREATE TABLE users ( id
MEDIUMINT NOT NULL
AUTO_INCREMENT, user_id
Varchar(30), age Number, status char(1),
PRIMARY KEY (id) )
Implicitly created on
first insert() operation. The primary
key _id is automatically added
if _id field is not specified.
db.users.insert( { user_id: "abc123",
age: 55, status: "A" } )
However, you can also explicitly create a
collection:
db.createCollection("users")
ALTER TABLE users ADD join_date
DATETIME
there is no structural alteration at the
collection level.
However, at the document
level, update() operations can add fields
to existing documents using
the $set operator.
1:- Create and alter
SQL to MongoDB Mapping Chart
SQL Schema Statements MongoDB Schema Statements
ALTER TABLE users DROP COLUMN
join_date
at the document
level, update() operations can remove
fields from documents using
the $unset operator.
db.users.update( { }, { $unset: {
join_date: "" } }, { multi: true } )
CREATE INDEX
idx_user_id_asc_age_desc ON
users(user_id, age DESC)
db.users.ensureIndex( { user_id: 1,
age: -1 } )
DROP TABLE users db.users.drop()
SQL to MongoDB Mapping Chart
2:- Insert
SQL INSERT Statements MongoDB insert() Statements
INSERT INTO users(user_id, age,
status) VALUES ("bcd001", 45, "A")
db.users.insert( { user_id: "bcd001",
age: 45, status: "A" } )
SQL to MongoDB Mapping Chart
3:- Select
SELECT user_id, status FROM users
db.users.find( { }, { user_id: 1, status: 1,
_id: 0 } )
SELECT * FROM users WHERE status
!= "A"
db.users.find( { status: { $ne: "A" } } )
SELECT * FROM users WHERE status
= "A" AND age = 50
db.users.find( { status: "A", age: 50 } )
SELECT * FROM users WHERE status
= "A" OR age = 50
db.users.find( { $or: [ { status: "A" } , {
age: 50 } ] } )
SELECT * FROM users WHERE age >
25 AND age <= 50
db.users.find( { age: { $gt: 25, $lte: 50 } } )
SQL to MongoDB Mapping Chart
3:- Select(Cont…)
SELECT * FROM users WHERE user_id
like "bc%"
db.users.find( { user_id: /^bc/ } )
SELECT * FROM users WHERE status =
"A" ORDER BY user_id DESC
db.users.find( { status: "A" } ).sort( {
user_id: -1 } )
SELECT COUNT(*) FROM users
db.users.count()
or
db.users.find().count()
SELECT COUNT(user_id) FROM users
db.users.count( { user_id: { $exists: true
} } )
or
db.users.find( { user_id: { $exists: true }
} ).count()
SQL to MongoDB Mapping Chart
3:- Select(Cont…)
SELECT DISTINCT(status) FROM users db.users.distinct( "status" )
SELECT * FROM users LIMIT 1
db.users.findOne()
or
db.users.find().limit(1)
SELECT * FROM users LIMIT 5 SKIP 10 db.users.find().limit(5).skip(10)
EXPLAIN SELECT * FROM users
WHERE status = "A"
db.users.find( { status: "A" } ).explain()
SQL to MongoDB Mapping Chart
4:- Update records
SQL Update Statements MongoDB update() Statements
UPDATE users SET status = "C"
WHERE age > 25
db.users.update( { age: { $gt: 25 } }, {
$set: { status: "C" } }, { multi: true } )
UPDATE users SET age = age + 3
WHERE status = "A"
db.users.update( { status: "A" } , {
$inc: { age: 3 } }, { multi: true } )
SQL to MongoDB Mapping Chart
5:- Delete records
SQL Delete Statements MongoDB remove() Statements
DELETE FROM users WHERE
status = "D"
db.users.remove( { status: "D" } )
DELETE FROM users db.users.remove({})
THANK YOU FOR READING
Dhaval M!5trY

More Related Content

What's hot (19)

PPTX
MongoDB Knowledge share
Mr Kyaing
 
PPT
ADO .Net
DrSonali Vyas
 
PPSX
MS SQL Server
Md. Mahedee Hasan
 
PPSX
ADO.NET
Farzad Wadia
 
PDF
The Ring programming language version 1.5.4 book - Part 28 of 185
Mahmoud Samir Fayed
 
PPT
ASP.NET 09 - ADO.NET
Randy Connolly
 
PPTX
Chapter 3: ado.net
Ngeam Soly
 
PPT
9781305078444 ppt ch05
Terry Yoast
 
PPT
ملخص تقنية تصميم صفحات الويب - الوحدة السادسة
جامعة القدس المفتوحة
 
ODP
Mongo indexes
paradokslabs
 
PDF
Local data storage for mobile apps
Ivano Malavolta
 
PDF
The Ring programming language version 1.9 book - Part 35 of 210
Mahmoud Samir Fayed
 
PPTX
MongoDB and Indexes - MUG Denver - 20160329
Douglas Duncan
 
PPTX
Oracle Database - JSON and the In-Memory Database
Marco Gralike
 
PPTX
Ado.net
Om Prakash
 
PPTX
Query Optimization in MongoDB
Hamoon Mohammadian Pour
 
PDF
Database Architecture and Basic Concepts
Tony Wong
 
PDF
Ado.net
Vikas Trivedi
 
PDF
JSON Data Parsing in Snowflake (By Faysal Shaarani)
Faysal Shaarani (MBA)
 
MongoDB Knowledge share
Mr Kyaing
 
ADO .Net
DrSonali Vyas
 
MS SQL Server
Md. Mahedee Hasan
 
ADO.NET
Farzad Wadia
 
The Ring programming language version 1.5.4 book - Part 28 of 185
Mahmoud Samir Fayed
 
ASP.NET 09 - ADO.NET
Randy Connolly
 
Chapter 3: ado.net
Ngeam Soly
 
9781305078444 ppt ch05
Terry Yoast
 
ملخص تقنية تصميم صفحات الويب - الوحدة السادسة
جامعة القدس المفتوحة
 
Mongo indexes
paradokslabs
 
Local data storage for mobile apps
Ivano Malavolta
 
The Ring programming language version 1.9 book - Part 35 of 210
Mahmoud Samir Fayed
 
MongoDB and Indexes - MUG Denver - 20160329
Douglas Duncan
 
Oracle Database - JSON and the In-Memory Database
Marco Gralike
 
Ado.net
Om Prakash
 
Query Optimization in MongoDB
Hamoon Mohammadian Pour
 
Database Architecture and Basic Concepts
Tony Wong
 
Ado.net
Vikas Trivedi
 
JSON Data Parsing in Snowflake (By Faysal Shaarani)
Faysal Shaarani (MBA)
 

Viewers also liked (20)

KEY
MongoDB hearts Django? (Django NYC)
Mike Dirolf
 
PPTX
Mango Database - Web Development
mssaman
 
PDF
Mongo db eveningschemadesign
MongoDB APAC
 
PPTX
Column oriented database
Kanike Krishna
 
PPTX
MongoDB Schema Design by Examples
Hadi Ariawan
 
PPT
Mongo db tutorials
Anuj Jain
 
KEY
Administration (Eliot Horowitz)
MongoSF
 
PPTX
MediaGlu and Mongo DB
Sundar Nathikudi
 
PPTX
Shankar's mongo db presentation
Shankar Kamble
 
PDF
Mongo db basics
Harischandra M K
 
PPTX
Connecting NodeJS & MongoDB
Enoch Joshua
 
PDF
NOSQL Overview
Tobias Lindaaker
 
PPT
Database Management system
Vijay Thorat
 
PPTX
NoSQL databases - An introduction
Pooyan Mehrparvar
 
PPTX
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
SpringPeople
 
PDF
Mongo db
Noman Ellahi
 
ZIP
NoSQL databases
Harri Kauhanen
 
PPTX
MongoDB for Beginners
Enoch Joshua
 
PPTX
Mongo DB
Karan Kukreja
 
MongoDB hearts Django? (Django NYC)
Mike Dirolf
 
Mango Database - Web Development
mssaman
 
Mongo db eveningschemadesign
MongoDB APAC
 
Column oriented database
Kanike Krishna
 
MongoDB Schema Design by Examples
Hadi Ariawan
 
Mongo db tutorials
Anuj Jain
 
Administration (Eliot Horowitz)
MongoSF
 
MediaGlu and Mongo DB
Sundar Nathikudi
 
Shankar's mongo db presentation
Shankar Kamble
 
Mongo db basics
Harischandra M K
 
Connecting NodeJS & MongoDB
Enoch Joshua
 
NOSQL Overview
Tobias Lindaaker
 
Database Management system
Vijay Thorat
 
NoSQL databases - An introduction
Pooyan Mehrparvar
 
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
SpringPeople
 
Mongo db
Noman Ellahi
 
NoSQL databases
Harri Kauhanen
 
MongoDB for Beginners
Enoch Joshua
 
Mongo DB
Karan Kukreja
 
Ad

Similar to Mongo db basics (20)

PPTX
171_74_216_Module_5-Non_relational_database_-mongodb.pptx
sukrithlal008
 
PPTX
Mongo db
Gyanendra Yadav
 
PPTX
Mongo db queries
ssuser6d5faa
 
PPTX
Introduction To MongoDB
ElieHannouch
 
PDF
MongoDB for Coder Training (Coding Serbia 2013)
Uwe Printz
 
PDF
Slide perkenalan dengan dasar MongoDB-query
amazaza49
 
PDF
MongoDB
wiTTyMinds1
 
PPTX
MongoDB_ppt.pptx
1AP18CS037ShirishKul
 
PDF
An introduction to MongoDB
Universidade de São Paulo
 
PPTX
Introduction to MongoDB
Raghunath A
 
PDF
Mongodb By Vipin
Vipin Mundayad
 
PDF
Experiment no 2
Ankit Dubey
 
PPTX
MongoDB introduction features -presentation - 2.pptx
sampathkumar546444
 
PPTX
Introduction to MongoDB.pptx
Surya937648
 
PPTX
MongoDB - An Introduction
dinkar thakur
 
PPTX
fard car.pptx
tarungupta276841
 
PPTX
Mongo db
Ramakrishna kapa
 
PPTX
MongoDB using Grails plugin by puneet behl
TO THE NEW | Technology
 
PPTX
Indexing Strategies to Help You Scale
MongoDB
 
PPTX
Webinar: What's new in the .NET Driver
MongoDB
 
171_74_216_Module_5-Non_relational_database_-mongodb.pptx
sukrithlal008
 
Mongo db
Gyanendra Yadav
 
Mongo db queries
ssuser6d5faa
 
Introduction To MongoDB
ElieHannouch
 
MongoDB for Coder Training (Coding Serbia 2013)
Uwe Printz
 
Slide perkenalan dengan dasar MongoDB-query
amazaza49
 
MongoDB
wiTTyMinds1
 
MongoDB_ppt.pptx
1AP18CS037ShirishKul
 
An introduction to MongoDB
Universidade de São Paulo
 
Introduction to MongoDB
Raghunath A
 
Mongodb By Vipin
Vipin Mundayad
 
Experiment no 2
Ankit Dubey
 
MongoDB introduction features -presentation - 2.pptx
sampathkumar546444
 
Introduction to MongoDB.pptx
Surya937648
 
MongoDB - An Introduction
dinkar thakur
 
fard car.pptx
tarungupta276841
 
MongoDB using Grails plugin by puneet behl
TO THE NEW | Technology
 
Indexing Strategies to Help You Scale
MongoDB
 
Webinar: What's new in the .NET Driver
MongoDB
 
Ad

Recently uploaded (20)

PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 

Mongo db basics

  • 2. INTRODUCTION • MongoDB is a schema-free document database written in C++ and developed in an open-source project which is mainly driven by the company 10gen Inc that also offers professional services around MongoDB. • the main goal of MongoDB is to close the gap between the fast and highly scalable key-/value-stores and feature-rich traditional RDBMSs relational database management systems. • A database contains one or more collections consisting of documents. • MongoDB is schema-free the documents within a collection may be heterogeneous although the • Once the first document is inserted into a database, a collection is created automatically and the inserted document is added to this collection. It store data (which is in BSON – “Binary Serialized Document Notation” ) format
  • 3. Advantage Documents are independent units which makes performance better (related data is read contiguously off disk) and makes it easier to distribute data across multiple servers. Application logic is easier to write. You don’t have to translate between objects in your application and SQL queries, you can just turn the object model directly into a document Non-relational databases are highly scalable than the relational databases. Non-relational databases process data faster than the relational databases because they do not use ACID properties. Non-relational databases are very flexible than the relational databases because they are schemaless.
  • 4. Disadvantage Non-relational databases are less reliable than the relational databases because they compromise reliability for performance. Non-relational databases alsocompromise consistency for performance In many non-relational databases security is lesser than relational databases which is a major concern. Like Mongodb and Cassandra both databases have lack of encryption for data files, they have very weak authentication system, and very simple authorization .
  • 5. INSTALLATION Step 1:- Download the latest production release of MongoDB Step 2:- Extract the downloaded archive. • In Windows Explorer, find the MongoDB download file, typically in the default Downloads directory. • Extract the archive to C: by right clicking on the archive and selecting Extract All and Step 3:- Move the MongoDB directory to another location. • cd • move C:mongodb-win32-* C:mongodb
  • 6. INSTALLATION(Cont…) Step 4:- Set Up the Data Directory Step 5:- Start MongoDB The default location for the MongoDB data directory is C:datadb. Create this folder using the Command Prompt. Go to the C: directory and issue the following command sequence: md data md datadb You can specify an alternate path for data files using the C:mongodbbinmongod.exe --dbpath d:testmongodbdata C:mongodbbinmongod.exe This will start the main MongoDB database process. The waiting for connections message in the console output indicates that the mongod.exe process is running successfully.
  • 7. INSTALLATION(Cont…) Step 6:- Connect to MongoDB Connect to MongoDB using the mongo.exe shell. C:mongodbbinmongo.exe The mongo.exe shell will connect to mongod.exe running on the localhost interface and port 27017 by default.
  • 8. BASIC OPERATIONS Oper 1:- Related to Database After starting the mongo shell your session will use the test database by default. • To show the name of current database -> DB • To display list of database -> show dbs • Switch to a new database named mydb or create new database -> use mydb NOTE:MongoDB will not permanently create a database until you insert data into that database.
  • 9. BASIC OPERATIONS(Cont…) Oper 2:- Create a Collection and Insert Documents • MongoDB uses dynamic schemas , you also need not specify the structure of your documents before inserting them into the collection. • Insert documents in testDb collection db.testDb.insert({x: 20}) db.testDb.insert({x: 25 , name: “mongo”}) • When you insert the first document, the mongod will create both a mydb database and the testData collection. • All MongoDB documents must have an _id field with a unique value. These operations do not explicitly specify a value for the _id field, so mongo creates a unique ObjectId value for the field before inserting it into the collection.
  • 10. BASIC OPERATIONS(Cont…) • To show list of collections in current database -> show collections • To show list of documents in collection -> db.testDb.find() • Query for Specific Documents -> db.testDb.find({x: 18}) • Limit the Number of Documents in the Result Set -> db.testDb.find().limit(3) Oper 3:- Update an existing document • In MongoDB, db.collection.update() and the db.collection.save() methods perform update operations.
  • 11. BASIC OPERATIONS(Cont…) •By default, the db.collection.update() method updates a single document. However, with the multi option, update() can update all documents in a collection that match a query. db.inventory.update( { type: "book", item : "journal" }, { $set : { qty: 10 } }, { upsert : true } ) •Call the update() method with the upsert flag to create a new document if no document matches the update’s query criteria.
  • 12. BASIC OPERATIONS(Cont…) By default, db.collection.remove() method removes all documents that match its query. However, the method can accept a flag to limit the delete operation to a single document. Oper 4:- Delete an existing document In MongoDB, db.collection.remove() method performs delete operations.
  • 13. Oper 5:- Fetching documents from collections BASIC OPERATIONS(Cont…)
  • 14. BASIC OPERATIONS(Cont…) Specifying an equality condition –> db.inventory.find( { type: "snacks" } ) Specify Conditions Using Query Operators -> db.inventory.find( { type: { $in: [ 'food', 'snacks' ] } } ) Specify AND Conditions -> db.inventory.find( { type: 'food', price: { $lt: 9.95 } } ) Specify OR Conditions -> db.inventory.find({ $or: [{ qty: { $gt: 100 } }, { price: { $lt: 9.95 } }]})
  • 16. BASIC TERMS • Queries in MongoDB return all fields in all matching documents by default. To limit the amount of data that MongoDB sends to applications, include a projection in the queries. 1:- Projection Exclude One Field From a Result Set db.records.find( { "user_id": { $lt: 42} }, { history: 0} ) NOTE : you cannot mix exclusive and inclusive projections , Except for excluding the _id field in inclusive projections. Return Two Fields and Exclude _id db.records.find( { "user_id": { $lt: 42} }, { "_id": 0, "name": 1 , "email": 1 } ) 2:- Cursors In the mongo shell, the primary method for the read operation is the db.collection.find() method. This method queries a collection and returns a cursor to the returning documents.
  • 17. SQL to MongoDB Mapping Chart SQL Terms/Concepts MongoDB Terms/Concepts database database table collection row document or BSON document column field index index table joins embedded documents and linking primary key Specify any unique column or column combination as primary key. primary key In MongoDB, the primary key is automatically set to the_id field.
  • 18. SQL to MongoDB Mapping Chart SQL Schema Statements MongoDB Schema Statements CREATE TABLE users ( id MEDIUMINT NOT NULL AUTO_INCREMENT, user_id Varchar(30), age Number, status char(1), PRIMARY KEY (id) ) Implicitly created on first insert() operation. The primary key _id is automatically added if _id field is not specified. db.users.insert( { user_id: "abc123", age: 55, status: "A" } ) However, you can also explicitly create a collection: db.createCollection("users") ALTER TABLE users ADD join_date DATETIME there is no structural alteration at the collection level. However, at the document level, update() operations can add fields to existing documents using the $set operator. 1:- Create and alter
  • 19. SQL to MongoDB Mapping Chart SQL Schema Statements MongoDB Schema Statements ALTER TABLE users DROP COLUMN join_date at the document level, update() operations can remove fields from documents using the $unset operator. db.users.update( { }, { $unset: { join_date: "" } }, { multi: true } ) CREATE INDEX idx_user_id_asc_age_desc ON users(user_id, age DESC) db.users.ensureIndex( { user_id: 1, age: -1 } ) DROP TABLE users db.users.drop()
  • 20. SQL to MongoDB Mapping Chart 2:- Insert SQL INSERT Statements MongoDB insert() Statements INSERT INTO users(user_id, age, status) VALUES ("bcd001", 45, "A") db.users.insert( { user_id: "bcd001", age: 45, status: "A" } )
  • 21. SQL to MongoDB Mapping Chart 3:- Select SELECT user_id, status FROM users db.users.find( { }, { user_id: 1, status: 1, _id: 0 } ) SELECT * FROM users WHERE status != "A" db.users.find( { status: { $ne: "A" } } ) SELECT * FROM users WHERE status = "A" AND age = 50 db.users.find( { status: "A", age: 50 } ) SELECT * FROM users WHERE status = "A" OR age = 50 db.users.find( { $or: [ { status: "A" } , { age: 50 } ] } ) SELECT * FROM users WHERE age > 25 AND age <= 50 db.users.find( { age: { $gt: 25, $lte: 50 } } )
  • 22. SQL to MongoDB Mapping Chart 3:- Select(Cont…) SELECT * FROM users WHERE user_id like "bc%" db.users.find( { user_id: /^bc/ } ) SELECT * FROM users WHERE status = "A" ORDER BY user_id DESC db.users.find( { status: "A" } ).sort( { user_id: -1 } ) SELECT COUNT(*) FROM users db.users.count() or db.users.find().count() SELECT COUNT(user_id) FROM users db.users.count( { user_id: { $exists: true } } ) or db.users.find( { user_id: { $exists: true } } ).count()
  • 23. SQL to MongoDB Mapping Chart 3:- Select(Cont…) SELECT DISTINCT(status) FROM users db.users.distinct( "status" ) SELECT * FROM users LIMIT 1 db.users.findOne() or db.users.find().limit(1) SELECT * FROM users LIMIT 5 SKIP 10 db.users.find().limit(5).skip(10) EXPLAIN SELECT * FROM users WHERE status = "A" db.users.find( { status: "A" } ).explain()
  • 24. SQL to MongoDB Mapping Chart 4:- Update records SQL Update Statements MongoDB update() Statements UPDATE users SET status = "C" WHERE age > 25 db.users.update( { age: { $gt: 25 } }, { $set: { status: "C" } }, { multi: true } ) UPDATE users SET age = age + 3 WHERE status = "A" db.users.update( { status: "A" } , { $inc: { age: 3 } }, { multi: true } )
  • 25. SQL to MongoDB Mapping Chart 5:- Delete records SQL Delete Statements MongoDB remove() Statements DELETE FROM users WHERE status = "D" db.users.remove( { status: "D" } ) DELETE FROM users db.users.remove({})
  • 26. THANK YOU FOR READING Dhaval M!5trY