SlideShare a Scribd company logo
ITERA UKRAINE 2017
Introduction to
MongoDB
ANTON FIL
https://university.mongodb.com/courses/M101J/about
• Introduction
• NoSQL
• CRUD
• Java driver
• Indexes
• Transactions
• Replication and sharding
AGENDA
What is MongoDB?
• MongoDB – is a free open-source cross-platform document-
oriented database program. Classified as NoSQL database, it uses
JSON-like documents.
• MongoDB is published under combination of GNU AGPL v3.0 and
Apache License v2.0 (for drivers).
Ranking of MongoDB
Complete ranking
Document stores
https://db-engines.com/en/ranking
Who uses MongoDB?
https://www.mongodb.com/who-uses-mongodb
Hosting of MongoDB
Free hostings are available:
1 DB, 512 MB, 3 Node Replica Set, Shared CPU/RAM
https://www.mongodb.com/cloud/atlas
https://mlab.com/plans/pricing/
What is NoSQL?
• NoSQL means “non sql”, “non relational”, sometimes “not only sql -
may support SQL-like languages queries”.
• Cluster-friendly. Triggered by the need of Google, Facebook to
process big data. NoSQL is much simpler for horizontal scaling to
clusters.
• Matching the data access patterns of your applications. The
data which is logically used together by application should be
aggregated into a single document.
• NoSQL simplifies the design of a databases. No schema. No
constraints.
Typical NoSQL document
{
'_id' : 1,
'name' : { 'first' : 'John', 'last' : 'Backus' },
'country': 'USA',
'contribs' : [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ],
'awards' : [
{
'award' : 'W.W. McDowell Award',
'year' : 1967,
'by' : 'IEEE Computer Society'
}, {
'award' : 'Draper Prize',
'year' : 1993,
'by' : 'National Academy of Engineering'
}
]
}
Shell and Server.
MongoDB distribution
contains 'client' and 'server'.
mongo.exe – Shell/Client
mongod.exe – Server
Database structure
MongoDB databases consist of collections. Collections consist
of documents.
• Collections vs tables
• Documents vs rows
• No Schema
JSON vs BSON
MongoDB stores documents as BSONs 16MB maximum.
http://bsonspec.org/spec.html
{"hello":"world"}
x16x00x00x00 // total document size
x02 // 0x02 = type String
hellox00 // field name with null terminator
x06x00x00x00 // size of value
worldx00 // field value with null terminator
x00 // 0x00 = type EOO ('end of object')
DEMO: HOW TO USE MONGO SHELL
CRUD
insertOne
insertMany
find updateOne
updateMany
replaceOne
deleteOne
deleteMany
Insert
db.contributors.insertOne({
'_id' : NumberInt(1),
'name' : { 'first' : 'John', 'last' : 'Backus' },
'country': 'USA',
'contribs' : [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ],
'awards' : [
{
'award' : 'W.W. McDowell Award',
'year' : 1967,
'by' : 'IEEE Computer Society'
}, {
'award' : 'Draper Prize',
'year' : 1993,
'by' : 'National Academy of Engineering'
}
]
});
{
'_id' : 1,
'name' : { 'first' : 'John', 'last' : 'Backus' },
'country': 'USA',
'contribs' : [ 'Fortran', 'ALGOL', 'FP' ],
'awards' : [
{
'award' : 'W.W. McDowell Award',
'year' : 1967,
'by' : 'IEEE Computer Society'
}, {
'award' : 'Draper Prize',
'year' : 1993,
'by' : 'National Academy of Engineering'
}
]
}
db.contributors.find({
_id:1
});
Find by id
{
'_id' : 1,
'name' : { 'first' : 'John', 'last' : 'Backus' },
'country': 'USA',
'contribs' : [ 'Fortran', 'ALGOL', 'FP' ],
'awards' : [
{
'award' : 'W.W. McDowell Award',
'year' : 1967,
'by' : 'IEEE Computer Society'
}, {
'award' : 'Draper Prize',
'year' : 1993,
'by' : 'National Academy of Engineering'
}
]
}
db.contributors.find({
'name.first':'John',
country: 'USA'
});
Find by several fields
{
'_id' : 1,
'name' : { 'first' : 'John', 'last' : 'Backus' },
'country': 'USA',
'contribs' : [ 'Fortran', 'ALGOL', 'FP' ],
'awards' : [
{
'award' : 'W.W. McDowell Award',
'year' : 1967,
'by' : 'IEEE Computer Society'
}, {
'award' : 'Draper Prize',
'year' : 1993,
'by' : 'National Academy of Engineering'
}
]
}
db.contributors.find({
contribs: 'ALGOL'
});
Find in array
{
'_id' : 1,
'name' : { 'first' : 'John', 'last' : 'Backus' },
'country': 'USA',
'contribs' : [ 'Fortran', 'ALGOL', 'FP' ],
'awards' : [
{
'award' : 'W.W. McDowell Award',
'year' : 1967,
'by' : 'IEEE Computer Society'
}, {
'award' : 'Draper Prize',
'year' : 1993,
'by' : 'National Academy of Engineering'
}
]
}
db.contributors.find({
'awards.1.year': 1993
});
Find in array at concrete index
{
'_id' : 1,
'name' : { 'first' : 'John', 'last' : 'Backus' },
'country': 'USA',
'contribs' : [ 'Fortran', 'ALGOL', 'FP' ],
'awards' : [
{
'award' : 'W.W. McDowell Award',
'year' : 1967,
'by' : 'IEEE Computer Society'
}, {
'award' : 'Draper Prize',
'year' : 1993,
'by' : 'National Academy of Engineering'
}
]
}
db.contributors.find({
'awards.year': {
$gt: 1990,
$lt: 1985
}
});
$eq, $gt, $gte, $lt, $lte, $ne,
$in, $nin
https://docs.mongodb.com/manual/reference/operator/query-comparison/
Find using comparison operators
{
'_id' : 1,
'name' : { 'first' : 'John', 'last' : 'Backus' },
'country': 'USA',
'contribs' : [ 'Fortran', 'ALGOL', 'FP' ],
'awards' : [
{
'award' : 'W.W. McDowell Award',
'year' : 1967,
'by' : 'IEEE Computer Society'
}, {
'award' : 'Draper Prize',
'year' : 1993,
'by' : 'National Academy of Engineering'
}
]
}
db.contributors.find({
$or: [
{'awards.year': {$gt: 1990}},
{'awards.year': {$lt: 1966}}
]
});
$or, $and, $not, $nor
https://docs.mongodb.com/manual/reference/operator/query-logical/
Find using logical operators
{
'_id' : 1,
'name' : { 'first' : 'John', 'last' : 'Backus' },
'country': 'USA',
'contribs' : [ 'Fortran', 'ALGOL', 'FP' ],
'awards' : [
{
'award' : 'W.W. McDowell Award',
'year' : 1967,
'by' : 'IEEE Computer Society'
}, {
'award' : 'Draper Prize',
'year' : 1993,
'by' : 'National Academy of Engineering'
}
]
}
db.contributors.find({
awards: {$elemMatch: {
year: {$gt: 1990, $lt: 1985}
}}
});
db.contributors.find({
contribs: {$all:['Fortran','ALGOL']}
});
db.contributors.find({awards: {$size:2}});
Find using array operators
{
'_id' : 1,
'name' : { 'first' : 'John', 'last' : 'Backus' },
'country': 'USA',
'contribs' : [ 'Fortran', 'ALGOL', 'FP' ],
'awards' : [
{
'award' : 'W.W. McDowell Award',
'year' : 1967,
'by' : 'IEEE Computer Society'
}, {
'award' : 'Draper Prize',
'year' : 1993,
'by' : 'National Academy of Engineering'
}
]
}
Projection allows to select only
specified document fields.
db.contributors.find(
{'name.first': 'John'},
{
'name.last': 1,
country: 1,
_id: 0
}
);
Projection
{
'_id' : 1,
'name' : { 'first' : 'John', 'last' : 'Backus' },
'country': 'USA',
'contribs' : [ 'Fortran', 'ALGOL', 'FP' ],
'awards' : [
{
'award' : 'W.W. McDowell Award',
'year' : 1967,
'by' : 'IEEE Computer Society'
}, {
'award' : 'Draper Prize',
'year' : 1993,
'by' : 'National Academy of Engineering'
}
]
}
db.contributors.updateOne(
{_id: 1},
{$set: {
'name.first': 'Mike',
country: 'Canada',
age: 60
}}
);
UpdateOne
{
'_id' : 1,
'name' : { 'first' : 'John', 'last' : 'Backus' },
'country': 'USA',
'contribs' : [ 'Fortran', 'ALGOL', 'FP' ],
'awards' : [
{
'award' : 'W.W. McDowell Award',
'year' : 1967,
'by' : 'IEEE Computer Society'
}, {
'award' : 'Draper Prize',
'year' : 1993,
'by' : 'National Academy of Engineering'
}
]
}
db.contributors.updateMany(
{},
{$inc: {
'awards.0.year': 3,
'awards.4.year': 7
}}
);
$inc, $mul, $rename,
$unset, $min, $max,…
https://docs.mongodb.com/manual/reference/operator/update-field/
UpdateMany
{
'_id' : 1,
'name' : { 'first' : 'John', 'last' : 'Backus' },
'country': 'USA',
'contribs' : [ 'Fortran', 'ALGOL', 'FP' ],
'awards' : [
{
'award' : 'W.W. McDowell Award',
'year' : 1967,
'by' : 'IEEE Computer Society'
}, {
'award' : 'Draper Prize',
'year' : 1993,
'by' : 'National Academy of Engineering'
}
]
}
db.contributors.updateOne(
{_id: 1},
{$push: {
awards: {
award: 'Best',
year: 1976,
by: 'MongoDB'
}
}}
);
Update arrays in documents
{
'_id' : 1,
'name' : { 'first' : 'John', 'last' : 'Backus' },
'country': 'USA',
'contribs' : [ 'Fortran', 'ALGOL', 'FP' ],
'awards' : [
{
'award' : 'W.W. McDowell Award',
'year' : 1967,
'by' : 'IEEE Computer Society'
}, {
'award' : 'Draper Prize',
'year' : 1993,
'by' : 'National Academy of Engineering'
}
]
}
db.contributors.updateOne(
{_id: 1},
{$push: {awards: {$each: [
{'award': 'A', 'year': '', 'by': ''},
{'award': 'B', 'year': '', 'by': ''}
]}}}
);
$push, $addToSet, $pop, $pull,…
https://docs.mongodb.com/manual/reference/operator/update-array/
Update arrays in documents
{
'_id' : 1,
'name' : { 'first' : 'John', 'last' : 'Backus' },
'country': 'USA',
'contribs' : [ 'Fortran', 'ALGOL', 'FP' ],
'awards' : [
{
'award' : 'W.W. McDowell Award',
'year' : 1967,
'by' : 'IEEE Computer Society'
}, {
'award' : 'Draper Prize',
'year' : 1993,
'by' : 'National Academy of Engineering'
}
]
}
db.contributors.updateOne(
{_id: 2},
{$push: {
awards: {
award: 'Best',
year: 1976,
by: 'MongoDB'
}
}},
{upsert: true}
);
Upsert
{
'_id' : 1,
'name' : { 'first' : 'John', 'last' : 'Backus' },
'country': 'USA',
'contribs' : [ 'Fortran', 'ALGOL', 'FP' ],
'awards' : [
{
'award' : 'W.W. McDowell Award',
'year' : 1967,
'by' : 'IEEE Computer Society'
}, {
'award' : 'Draper Prize',
'year' : 1993,
'by' : 'National Academy of Engineering'
}
]
}
db.contributors.replaceOne(
{_id: 1},
{$push: {
awards: {
award: 'Best',
year: 1976,
by: 'MongoDB'
}
}}
);
ReplaceOne
https://docs.mongodb.com/manual/aggregation/
SQL Terms, Functions, and Concepts MongoDB Aggregation Operators
WHERE $match
GROUP BY $group
HAVING $match
SELECT $project
ORDER BY $sort
LIMIT $limit
SUM() $sum
COUNT() $sum
join
$lookup
New in version 3.2.
Aggregation framework
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.5.0</version>
</dependency>
final MongoClient mongoClient = new MongoClient(
new MongoClientURI("mongodb://localhost:27017"));
final MongoDatabase db = mongoClient.getDatabase("programming");
final MongoCollection<Document> coll = db.getCollection("contributors");
Document query = new Document().append("_id", 1);
Document contributor = coll.find(query).first();
mongoClient.close();
Connect to MongoDB using Java
coll.insertOne(contributor);
coll.insertMany(Arrays.asList(contributor1, contributor2));
coll.updateOne(...);
coll.updateMany(...);
coll.replaceOne(...);
coll.deleteOne(...);
coll.deleteMany(...);
CRUD in Java
import static com.mongodb.client.model.Filters.gt;
import static com.mongodb.client.model.Filters.lt;
import static com.mongodb.client.model.Filters.or;
import static com.mongodb.client.model.Projections.exclude;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import static com.mongodb.client.model.Sorts.ascending;
import static com.mongodb.client.model.Sorts.descending;
import static com.mongodb.client.model.Sorts.orderBy;
...
List<Document> all = coll.find(or(gt("awards.year", 1990), lt("awards.year", 1966)))
.projection(fields(include("name.last", "country"), exclude("_id")))
.sort(orderBy(ascending("_id"), descending("name.first", "name.last")))
.skip(20)
.limit(10)
.into(new ArrayList<>());
Constructing queries in Java
import static com.mongodb.client.model.Updates.combine;
import static com.mongodb.client.model.Updates.inc;
import static com.mongodb.client.model.Updates.push;
import static com.mongodb.client.model.Updates.set;
...
coll.updateOne(
eq("_id", 1),
combine(set("name.first", "Anton"),
set("age", 30),
push("contribs", "Java"),
inc("awards.0.year", 1000))
);
Updating documents in Java
ODM vs ORM
Morphia
https://mongodb.github.io/morphia/
Spring Data MongoDB
https://projects.spring.io/spring-data-mongodb/
Performance
Storage engine is an interface between MongoDB server and Disk.
It determines data file format and format of indexes.
MMAPv1 – slow one, acquires collection-level lock during writes.
WiredTiger – fast one, uses document-level locking.
Indexes
Indexes increase search speed but descrease insert speed.
In MongoDB indexes are Btree separate data structures with
references to positions of documents.
Examples of indexes
for (var i = 0; i < 1000000; i++) {
db.people.insert({
name: 'Mike',
age: i
});
}
db.people.createIndex({name: 1, age: 1});
db.people.explain(true).find().sort({name: 1, age: 1}).limit(1); //Will use index
db.people.explain().find().sort({name: -1, age: -1}).limit(1); //Will use index
db.people.explain().find().sort({name: 1}).limit(1); //Will use index
db.people.explain().find().sort({name: -1}).limit(1); //Will use index
db.people.explain(true).find().sort({age: 1}).limit(1); //Will not use index
db.people.explain().find().sort({age: -1}).limit(1); //Will not use index
db.people.explain().find().sort({name: -1, age: 1}).limit(1); //Will not use index
db.people.explain().find().sort({name: 1, age: -1}).limit(1); //Will not use index
Transactions
• There are no Transactions
• There are atomic operations
• Update of each document is atomic. Document level locking is used.
Bulk update is not atomic.
• $isolated operator can be used to acquire lock on a the collection level
and make bulk update synchronized.
db.contributors.updateMany(
{'name.first': 'John', $isolated : 1},
{$set: {'name.first': 'Mike'}}
);
Write concern
Application
MongoDB
RAM
Pages
Journal
DISK
read
write
read
flush
flush
Acknowledgement
behavior
w=1
j=0
In RAM
w=1
j=1
On disk
w=0 No
acknowledgement
deprecated
On the level of client, collection and command we can set two parameters w/j.
Replication
mongod
(primary)
[oplog]
Application
mongod
(secondary)
[oplog]
mongod
(secondary)
[oplog]
read
Replication increases data availability and provides a level of fault tolerance
against the loss of a single database server. It also provide increased read
capacity.
Write concern
w=0,1,2,…,n, majority
j=0,1
Creating replica sets on Windows
start mongod --replSet rs1 --logpath 1.log --dbpath datars1 --port 27017 --smallfiles --oplogSize 64
start mongod --replSet rs1 --logpath 2.log --dbpath datars2 --port 27018 --smallfiles --oplogSize 64
start mongod --replSet rs1 --logpath 3.log --dbpath datars3 --port 27019 --smallfiles --oplogSize 64
mongo --port 27017
config = {_id: "rs1", members: [
{_id: 0, host: "localhost:27017"},
{_id: 1, host: "localhost:27018"},
{_id: 2, host: "localhost:27019"}
]};
rs.initiate(config);
rs.status();
Connect to replica sets from Java
mongoClient = new MongoClient(
Arrays.asList(
new ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)),
MongoClientOptions.builder()
.requiredReplicaSetName("rs1")
.readPreference(ReadPreference.secondaryPreferred())
.writeConcern(WriteConcern.W1.withJournal(true))
.build());
Sharding
Sharding – is a method for
splitting single collection
across multiple servers.
It provides support of very
large data sets and high
throughput of operations.
To split collection across
multiple servers a collection
shard key should be
provided.
• MongoDB provides extensive and
intuitively understandable query
language which is not inferior to the
SQL
• MongoDB provides extensive
capabilities for investigation of queries
execution plans and performance
issues including sharded environments
• MongoDB provides extensive
capabilities for Replication and
Sharding
CONCLUSION
Introduction to MongoDB

More Related Content

What's hot (18)

ODP
Contando uma história com O.O.
Vagner Zampieri
 
PPTX
MongoDB + Java - Everything you need to know
Norberto Leite
 
KEY
Geospatial Indexing and Querying with MongoDB
Grant Goodale
 
PDF
Embedding a language into string interpolator
Michael Limansky
 
PDF
Hidden Treasures of the Python Standard Library
doughellmann
 
KEY
MongoDB Java Development - MongoBoston 2010
Eliot Horowitz
 
PPTX
MongoDB: Easy Java Persistence with Morphia
Scott Hernandez
 
PDF
2012-08-29 - NoSQL Bootcamp (Redis, RavenDB & MongoDB für .NET Entwickler)
Johannes Hoppe
 
PDF
Internet of Information and Services (IoIS): A Conceptual Integrative Archite...
Antonio Marcos Alberti
 
ODP
Database2
Claudio Guidi
 
PDF
Polyglot Persistence
Scott Leberknight
 
PPTX
NoSQL Search Roadshow Zurich 2013 - Polyglot persistence with no sql
Michael Lehmann
 
PPT
Building Your First App with MongoDB
MongoDB
 
PPTX
Java Development with MongoDB
Scott Hernandez
 
PPTX
Aggregation in MongoDB
Kishor Parkhe
 
PPTX
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
MongoDB
 
PPTX
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
MongoDB
 
PDF
Latinoware
kchodorow
 
Contando uma história com O.O.
Vagner Zampieri
 
MongoDB + Java - Everything you need to know
Norberto Leite
 
Geospatial Indexing and Querying with MongoDB
Grant Goodale
 
Embedding a language into string interpolator
Michael Limansky
 
Hidden Treasures of the Python Standard Library
doughellmann
 
MongoDB Java Development - MongoBoston 2010
Eliot Horowitz
 
MongoDB: Easy Java Persistence with Morphia
Scott Hernandez
 
2012-08-29 - NoSQL Bootcamp (Redis, RavenDB & MongoDB für .NET Entwickler)
Johannes Hoppe
 
Internet of Information and Services (IoIS): A Conceptual Integrative Archite...
Antonio Marcos Alberti
 
Database2
Claudio Guidi
 
Polyglot Persistence
Scott Leberknight
 
NoSQL Search Roadshow Zurich 2013 - Polyglot persistence with no sql
Michael Lehmann
 
Building Your First App with MongoDB
MongoDB
 
Java Development with MongoDB
Scott Hernandez
 
Aggregation in MongoDB
Kishor Parkhe
 
Back to Basics Webinar 4: Advanced Indexing, Text and Geospatial Indexes
MongoDB
 
Webinaire 2 de la série « Retour aux fondamentaux » : Votre première applicat...
MongoDB
 
Latinoware
kchodorow
 

Similar to Introduction to MongoDB (20)

PDF
Mongo db
Toki Kanno
 
PDF
Mongo db basics
Harischandra M K
 
PDF
Mongo DB schema design patterns
joergreichert
 
PPS
MongoDB crud
Darshan Jayarama
 
PPTX
Mongo DB 102
Abhijeet Vaikar
 
PPTX
Mongodb introduction and_internal(simple)
Kai Zhao
 
PPTX
Introduction to MongoDB
S.Shayan Daneshvar
 
PPTX
lecture_34e.pptx
janibashashaik25
 
PPTX
Mongo DB Presentation
Jaya Naresh Kovela
 
PPTX
MongoDB - Features and Operations
ramyaranjith
 
PDF
mongodb-introduction
Tse-Ching Ho
 
PPTX
MongoDB_ppt.pptx
1AP18CS037ShirishKul
 
PDF
MongoDB.pdf54teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeer
MdRiyad22
 
PPTX
MongoDB - An Introduction
dinkar thakur
 
PPTX
Copy of MongoDB .pptx
nehabsairam
 
PPTX
MongoDB's index and query optimize
mysqlops
 
PPTX
Indexing and Query Optimizer (Aaron Staple)
MongoSF
 
PPTX
Mongo Nosql CRUD Operations
anujaggarwal49
 
PPTX
Mondodb
Paulo Fagundes
 
PDF
10gen Presents Schema Design and Data Modeling
DATAVERSITY
 
Mongo db
Toki Kanno
 
Mongo db basics
Harischandra M K
 
Mongo DB schema design patterns
joergreichert
 
MongoDB crud
Darshan Jayarama
 
Mongo DB 102
Abhijeet Vaikar
 
Mongodb introduction and_internal(simple)
Kai Zhao
 
Introduction to MongoDB
S.Shayan Daneshvar
 
lecture_34e.pptx
janibashashaik25
 
Mongo DB Presentation
Jaya Naresh Kovela
 
MongoDB - Features and Operations
ramyaranjith
 
mongodb-introduction
Tse-Ching Ho
 
MongoDB_ppt.pptx
1AP18CS037ShirishKul
 
MongoDB.pdf54teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeer
MdRiyad22
 
MongoDB - An Introduction
dinkar thakur
 
Copy of MongoDB .pptx
nehabsairam
 
MongoDB's index and query optimize
mysqlops
 
Indexing and Query Optimizer (Aaron Staple)
MongoSF
 
Mongo Nosql CRUD Operations
anujaggarwal49
 
10gen Presents Schema Design and Data Modeling
DATAVERSITY
 
Ad

Recently uploaded (20)

PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Ad

Introduction to MongoDB

  • 1. ITERA UKRAINE 2017 Introduction to MongoDB ANTON FIL
  • 2. https://university.mongodb.com/courses/M101J/about • Introduction • NoSQL • CRUD • Java driver • Indexes • Transactions • Replication and sharding AGENDA
  • 3. What is MongoDB? • MongoDB – is a free open-source cross-platform document- oriented database program. Classified as NoSQL database, it uses JSON-like documents. • MongoDB is published under combination of GNU AGPL v3.0 and Apache License v2.0 (for drivers).
  • 4. Ranking of MongoDB Complete ranking Document stores https://db-engines.com/en/ranking
  • 6. Hosting of MongoDB Free hostings are available: 1 DB, 512 MB, 3 Node Replica Set, Shared CPU/RAM https://www.mongodb.com/cloud/atlas https://mlab.com/plans/pricing/
  • 7. What is NoSQL? • NoSQL means “non sql”, “non relational”, sometimes “not only sql - may support SQL-like languages queries”. • Cluster-friendly. Triggered by the need of Google, Facebook to process big data. NoSQL is much simpler for horizontal scaling to clusters. • Matching the data access patterns of your applications. The data which is logically used together by application should be aggregated into a single document. • NoSQL simplifies the design of a databases. No schema. No constraints.
  • 8. Typical NoSQL document { '_id' : 1, 'name' : { 'first' : 'John', 'last' : 'Backus' }, 'country': 'USA', 'contribs' : [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ], 'awards' : [ { 'award' : 'W.W. McDowell Award', 'year' : 1967, 'by' : 'IEEE Computer Society' }, { 'award' : 'Draper Prize', 'year' : 1993, 'by' : 'National Academy of Engineering' } ] }
  • 9. Shell and Server. MongoDB distribution contains 'client' and 'server'. mongo.exe – Shell/Client mongod.exe – Server
  • 10. Database structure MongoDB databases consist of collections. Collections consist of documents. • Collections vs tables • Documents vs rows • No Schema
  • 11. JSON vs BSON MongoDB stores documents as BSONs 16MB maximum. http://bsonspec.org/spec.html {"hello":"world"} x16x00x00x00 // total document size x02 // 0x02 = type String hellox00 // field name with null terminator x06x00x00x00 // size of value worldx00 // field value with null terminator x00 // 0x00 = type EOO ('end of object')
  • 12. DEMO: HOW TO USE MONGO SHELL
  • 14. Insert db.contributors.insertOne({ '_id' : NumberInt(1), 'name' : { 'first' : 'John', 'last' : 'Backus' }, 'country': 'USA', 'contribs' : [ 'Fortran', 'ALGOL', 'Backus-Naur Form', 'FP' ], 'awards' : [ { 'award' : 'W.W. McDowell Award', 'year' : 1967, 'by' : 'IEEE Computer Society' }, { 'award' : 'Draper Prize', 'year' : 1993, 'by' : 'National Academy of Engineering' } ] });
  • 15. { '_id' : 1, 'name' : { 'first' : 'John', 'last' : 'Backus' }, 'country': 'USA', 'contribs' : [ 'Fortran', 'ALGOL', 'FP' ], 'awards' : [ { 'award' : 'W.W. McDowell Award', 'year' : 1967, 'by' : 'IEEE Computer Society' }, { 'award' : 'Draper Prize', 'year' : 1993, 'by' : 'National Academy of Engineering' } ] } db.contributors.find({ _id:1 }); Find by id
  • 16. { '_id' : 1, 'name' : { 'first' : 'John', 'last' : 'Backus' }, 'country': 'USA', 'contribs' : [ 'Fortran', 'ALGOL', 'FP' ], 'awards' : [ { 'award' : 'W.W. McDowell Award', 'year' : 1967, 'by' : 'IEEE Computer Society' }, { 'award' : 'Draper Prize', 'year' : 1993, 'by' : 'National Academy of Engineering' } ] } db.contributors.find({ 'name.first':'John', country: 'USA' }); Find by several fields
  • 17. { '_id' : 1, 'name' : { 'first' : 'John', 'last' : 'Backus' }, 'country': 'USA', 'contribs' : [ 'Fortran', 'ALGOL', 'FP' ], 'awards' : [ { 'award' : 'W.W. McDowell Award', 'year' : 1967, 'by' : 'IEEE Computer Society' }, { 'award' : 'Draper Prize', 'year' : 1993, 'by' : 'National Academy of Engineering' } ] } db.contributors.find({ contribs: 'ALGOL' }); Find in array
  • 18. { '_id' : 1, 'name' : { 'first' : 'John', 'last' : 'Backus' }, 'country': 'USA', 'contribs' : [ 'Fortran', 'ALGOL', 'FP' ], 'awards' : [ { 'award' : 'W.W. McDowell Award', 'year' : 1967, 'by' : 'IEEE Computer Society' }, { 'award' : 'Draper Prize', 'year' : 1993, 'by' : 'National Academy of Engineering' } ] } db.contributors.find({ 'awards.1.year': 1993 }); Find in array at concrete index
  • 19. { '_id' : 1, 'name' : { 'first' : 'John', 'last' : 'Backus' }, 'country': 'USA', 'contribs' : [ 'Fortran', 'ALGOL', 'FP' ], 'awards' : [ { 'award' : 'W.W. McDowell Award', 'year' : 1967, 'by' : 'IEEE Computer Society' }, { 'award' : 'Draper Prize', 'year' : 1993, 'by' : 'National Academy of Engineering' } ] } db.contributors.find({ 'awards.year': { $gt: 1990, $lt: 1985 } }); $eq, $gt, $gte, $lt, $lte, $ne, $in, $nin https://docs.mongodb.com/manual/reference/operator/query-comparison/ Find using comparison operators
  • 20. { '_id' : 1, 'name' : { 'first' : 'John', 'last' : 'Backus' }, 'country': 'USA', 'contribs' : [ 'Fortran', 'ALGOL', 'FP' ], 'awards' : [ { 'award' : 'W.W. McDowell Award', 'year' : 1967, 'by' : 'IEEE Computer Society' }, { 'award' : 'Draper Prize', 'year' : 1993, 'by' : 'National Academy of Engineering' } ] } db.contributors.find({ $or: [ {'awards.year': {$gt: 1990}}, {'awards.year': {$lt: 1966}} ] }); $or, $and, $not, $nor https://docs.mongodb.com/manual/reference/operator/query-logical/ Find using logical operators
  • 21. { '_id' : 1, 'name' : { 'first' : 'John', 'last' : 'Backus' }, 'country': 'USA', 'contribs' : [ 'Fortran', 'ALGOL', 'FP' ], 'awards' : [ { 'award' : 'W.W. McDowell Award', 'year' : 1967, 'by' : 'IEEE Computer Society' }, { 'award' : 'Draper Prize', 'year' : 1993, 'by' : 'National Academy of Engineering' } ] } db.contributors.find({ awards: {$elemMatch: { year: {$gt: 1990, $lt: 1985} }} }); db.contributors.find({ contribs: {$all:['Fortran','ALGOL']} }); db.contributors.find({awards: {$size:2}}); Find using array operators
  • 22. { '_id' : 1, 'name' : { 'first' : 'John', 'last' : 'Backus' }, 'country': 'USA', 'contribs' : [ 'Fortran', 'ALGOL', 'FP' ], 'awards' : [ { 'award' : 'W.W. McDowell Award', 'year' : 1967, 'by' : 'IEEE Computer Society' }, { 'award' : 'Draper Prize', 'year' : 1993, 'by' : 'National Academy of Engineering' } ] } Projection allows to select only specified document fields. db.contributors.find( {'name.first': 'John'}, { 'name.last': 1, country: 1, _id: 0 } ); Projection
  • 23. { '_id' : 1, 'name' : { 'first' : 'John', 'last' : 'Backus' }, 'country': 'USA', 'contribs' : [ 'Fortran', 'ALGOL', 'FP' ], 'awards' : [ { 'award' : 'W.W. McDowell Award', 'year' : 1967, 'by' : 'IEEE Computer Society' }, { 'award' : 'Draper Prize', 'year' : 1993, 'by' : 'National Academy of Engineering' } ] } db.contributors.updateOne( {_id: 1}, {$set: { 'name.first': 'Mike', country: 'Canada', age: 60 }} ); UpdateOne
  • 24. { '_id' : 1, 'name' : { 'first' : 'John', 'last' : 'Backus' }, 'country': 'USA', 'contribs' : [ 'Fortran', 'ALGOL', 'FP' ], 'awards' : [ { 'award' : 'W.W. McDowell Award', 'year' : 1967, 'by' : 'IEEE Computer Society' }, { 'award' : 'Draper Prize', 'year' : 1993, 'by' : 'National Academy of Engineering' } ] } db.contributors.updateMany( {}, {$inc: { 'awards.0.year': 3, 'awards.4.year': 7 }} ); $inc, $mul, $rename, $unset, $min, $max,… https://docs.mongodb.com/manual/reference/operator/update-field/ UpdateMany
  • 25. { '_id' : 1, 'name' : { 'first' : 'John', 'last' : 'Backus' }, 'country': 'USA', 'contribs' : [ 'Fortran', 'ALGOL', 'FP' ], 'awards' : [ { 'award' : 'W.W. McDowell Award', 'year' : 1967, 'by' : 'IEEE Computer Society' }, { 'award' : 'Draper Prize', 'year' : 1993, 'by' : 'National Academy of Engineering' } ] } db.contributors.updateOne( {_id: 1}, {$push: { awards: { award: 'Best', year: 1976, by: 'MongoDB' } }} ); Update arrays in documents
  • 26. { '_id' : 1, 'name' : { 'first' : 'John', 'last' : 'Backus' }, 'country': 'USA', 'contribs' : [ 'Fortran', 'ALGOL', 'FP' ], 'awards' : [ { 'award' : 'W.W. McDowell Award', 'year' : 1967, 'by' : 'IEEE Computer Society' }, { 'award' : 'Draper Prize', 'year' : 1993, 'by' : 'National Academy of Engineering' } ] } db.contributors.updateOne( {_id: 1}, {$push: {awards: {$each: [ {'award': 'A', 'year': '', 'by': ''}, {'award': 'B', 'year': '', 'by': ''} ]}}} ); $push, $addToSet, $pop, $pull,… https://docs.mongodb.com/manual/reference/operator/update-array/ Update arrays in documents
  • 27. { '_id' : 1, 'name' : { 'first' : 'John', 'last' : 'Backus' }, 'country': 'USA', 'contribs' : [ 'Fortran', 'ALGOL', 'FP' ], 'awards' : [ { 'award' : 'W.W. McDowell Award', 'year' : 1967, 'by' : 'IEEE Computer Society' }, { 'award' : 'Draper Prize', 'year' : 1993, 'by' : 'National Academy of Engineering' } ] } db.contributors.updateOne( {_id: 2}, {$push: { awards: { award: 'Best', year: 1976, by: 'MongoDB' } }}, {upsert: true} ); Upsert
  • 28. { '_id' : 1, 'name' : { 'first' : 'John', 'last' : 'Backus' }, 'country': 'USA', 'contribs' : [ 'Fortran', 'ALGOL', 'FP' ], 'awards' : [ { 'award' : 'W.W. McDowell Award', 'year' : 1967, 'by' : 'IEEE Computer Society' }, { 'award' : 'Draper Prize', 'year' : 1993, 'by' : 'National Academy of Engineering' } ] } db.contributors.replaceOne( {_id: 1}, {$push: { awards: { award: 'Best', year: 1976, by: 'MongoDB' } }} ); ReplaceOne
  • 29. https://docs.mongodb.com/manual/aggregation/ SQL Terms, Functions, and Concepts MongoDB Aggregation Operators WHERE $match GROUP BY $group HAVING $match SELECT $project ORDER BY $sort LIMIT $limit SUM() $sum COUNT() $sum join $lookup New in version 3.2. Aggregation framework
  • 30. <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.5.0</version> </dependency> final MongoClient mongoClient = new MongoClient( new MongoClientURI("mongodb://localhost:27017")); final MongoDatabase db = mongoClient.getDatabase("programming"); final MongoCollection<Document> coll = db.getCollection("contributors"); Document query = new Document().append("_id", 1); Document contributor = coll.find(query).first(); mongoClient.close(); Connect to MongoDB using Java
  • 32. import static com.mongodb.client.model.Filters.gt; import static com.mongodb.client.model.Filters.lt; import static com.mongodb.client.model.Filters.or; import static com.mongodb.client.model.Projections.exclude; import static com.mongodb.client.model.Projections.fields; import static com.mongodb.client.model.Projections.include; import static com.mongodb.client.model.Sorts.ascending; import static com.mongodb.client.model.Sorts.descending; import static com.mongodb.client.model.Sorts.orderBy; ... List<Document> all = coll.find(or(gt("awards.year", 1990), lt("awards.year", 1966))) .projection(fields(include("name.last", "country"), exclude("_id"))) .sort(orderBy(ascending("_id"), descending("name.first", "name.last"))) .skip(20) .limit(10) .into(new ArrayList<>()); Constructing queries in Java
  • 33. import static com.mongodb.client.model.Updates.combine; import static com.mongodb.client.model.Updates.inc; import static com.mongodb.client.model.Updates.push; import static com.mongodb.client.model.Updates.set; ... coll.updateOne( eq("_id", 1), combine(set("name.first", "Anton"), set("age", 30), push("contribs", "Java"), inc("awards.0.year", 1000)) ); Updating documents in Java
  • 36. Performance Storage engine is an interface between MongoDB server and Disk. It determines data file format and format of indexes. MMAPv1 – slow one, acquires collection-level lock during writes. WiredTiger – fast one, uses document-level locking.
  • 37. Indexes Indexes increase search speed but descrease insert speed. In MongoDB indexes are Btree separate data structures with references to positions of documents.
  • 38. Examples of indexes for (var i = 0; i < 1000000; i++) { db.people.insert({ name: 'Mike', age: i }); } db.people.createIndex({name: 1, age: 1}); db.people.explain(true).find().sort({name: 1, age: 1}).limit(1); //Will use index db.people.explain().find().sort({name: -1, age: -1}).limit(1); //Will use index db.people.explain().find().sort({name: 1}).limit(1); //Will use index db.people.explain().find().sort({name: -1}).limit(1); //Will use index db.people.explain(true).find().sort({age: 1}).limit(1); //Will not use index db.people.explain().find().sort({age: -1}).limit(1); //Will not use index db.people.explain().find().sort({name: -1, age: 1}).limit(1); //Will not use index db.people.explain().find().sort({name: 1, age: -1}).limit(1); //Will not use index
  • 39. Transactions • There are no Transactions • There are atomic operations • Update of each document is atomic. Document level locking is used. Bulk update is not atomic. • $isolated operator can be used to acquire lock on a the collection level and make bulk update synchronized. db.contributors.updateMany( {'name.first': 'John', $isolated : 1}, {$set: {'name.first': 'Mike'}} );
  • 40. Write concern Application MongoDB RAM Pages Journal DISK read write read flush flush Acknowledgement behavior w=1 j=0 In RAM w=1 j=1 On disk w=0 No acknowledgement deprecated On the level of client, collection and command we can set two parameters w/j.
  • 41. Replication mongod (primary) [oplog] Application mongod (secondary) [oplog] mongod (secondary) [oplog] read Replication increases data availability and provides a level of fault tolerance against the loss of a single database server. It also provide increased read capacity. Write concern w=0,1,2,…,n, majority j=0,1
  • 42. Creating replica sets on Windows start mongod --replSet rs1 --logpath 1.log --dbpath datars1 --port 27017 --smallfiles --oplogSize 64 start mongod --replSet rs1 --logpath 2.log --dbpath datars2 --port 27018 --smallfiles --oplogSize 64 start mongod --replSet rs1 --logpath 3.log --dbpath datars3 --port 27019 --smallfiles --oplogSize 64 mongo --port 27017 config = {_id: "rs1", members: [ {_id: 0, host: "localhost:27017"}, {_id: 1, host: "localhost:27018"}, {_id: 2, host: "localhost:27019"} ]}; rs.initiate(config); rs.status();
  • 43. Connect to replica sets from Java mongoClient = new MongoClient( Arrays.asList( new ServerAddress("localhost", 27017), new ServerAddress("localhost", 27018), new ServerAddress("localhost", 27019)), MongoClientOptions.builder() .requiredReplicaSetName("rs1") .readPreference(ReadPreference.secondaryPreferred()) .writeConcern(WriteConcern.W1.withJournal(true)) .build());
  • 44. Sharding Sharding – is a method for splitting single collection across multiple servers. It provides support of very large data sets and high throughput of operations. To split collection across multiple servers a collection shard key should be provided.
  • 45. • MongoDB provides extensive and intuitively understandable query language which is not inferior to the SQL • MongoDB provides extensive capabilities for investigation of queries execution plans and performance issues including sharded environments • MongoDB provides extensive capabilities for Replication and Sharding CONCLUSION

Editor's Notes

  • #4: This is Community version of MongoDB. GNU AGPL v3.0 – copyleft is required. Changes to the source code/distribution of 'mongod' and/or 'mongoc' should be left back to the MongoDB community. Apache License – copyleft is not required. Both GNU AGPL v3.0 and Apache License can be used in commercial projects for free.
  • #8: When Matching the data access patterns of your applications be careful when breaking 3rd normal form. If we want to rename something (e.g. author email) it shouldn't influence the whole database. No constraints like foreign keys. Embedding documents helps.
  • #10: mongod by default saves data in 'C:\data\db' directory which should be created before starting mongod. You can specify you own directory by running 'mongod –dbpath C:\data_1'.
  • #20: For each of two conditions ($gt and $lt) array 'awards' must contain element which satisfies this single condition.
  • #28: If no documents matched the filter then a new document is inserted into the collection.
  • #29: Replaces matched document with a given one. Can also take {upsert: true} option.