SlideShare a Scribd company logo
1 of 33
Application Development Series
Back to Basics
Interacting with the database

Daniel Roberts
@dmroberts
#MongoDBBasics
Agenda
• Recap from last session
• MongoDB Inserts & Queries
– ObjectId
– Returning documents – cursors
– Projections

• MongoDB Update operators
– Fixed Buckets
– Pre Aggregated Reports

• Write Concern
– Durability vs Performance trade off
2
Q&A
• Virtual Genius Bar
– Use the chat to post
questions
– EMEA Solution
Architecture / Support
team are on hand
– Make use of them
during the sessions!!!
3
Recap from last time….
Architecture
• Looked at the application architecture
– JSON / RESTful
– Python based

HTTP(S) REST

Client-side
JSON

Python web
app
(BSON)

(eg AngularJS)
Pymongo driver

5
Schema and Architecture
• Schema design
– Modeled
•
•
•
•

6

Articles
Comments
Interactions
Users
Modeling Articles
Articles collection
def get_article(article_id)
def get_articles():
def create_article():

METHODS

{
'_id' :
'text':

• Posting articles
•

'Article content…',

'date' : ISODate(...),

insert

'title' :

• Get List of articles
•

ObjectId(...),

‟Intro to MongoDB',

'author' : 'Dan Roberts',

Return Cursor

'tags' :

• Get individual article

[

]
}

7

'mongodb',
'database',
'nosql‟
Modeling Comments
Comments collection
METHODS

def add_comment(article_id):
def get_comments(article_id):

{

• Storing comments
• Quickly retrieve most
recent comments
• Add new comments
to document
• „Bucketing‟

8

„_id‟ : ObjectId(..),
„article_id‟ : ObjectId(..),
„page‟ : 1,
„count‟ : 42
„comments‟ : [
{
„text‟ : „A great
article, helped me understand
schema design‟,
„date‟ : ISODate(..),
„author‟ : „johnsmith‟
},
…
}
Modeling Interactions
Interactions collection
METHODS

def add_interaction(article_id, type):

{
„_id‟ : ObjectId(..),
„article_id‟ : ObjectId(..),
„section‟ : „schema‟,
„date‟ : ISODate(..),
„daily‟: { „views‟ : 45,
„comments‟ : 150 }
„hours‟ : {
0:{
„views‟ : 10 },
1:{
„views‟ : 2 },
…
23 : { „views‟ : 14,
„comments‟ : 10 }
}

• Used for reporting on
articles
• Create “preaggregated” reports

}

9
Inserting / Querying
Inserting documents
• Driver generates ObjectId() for _id
– if not specified
– 12 bytes - 4-byte

epoch, 3-byte machine id, a 2-byte process id, and a 3-byte

counter.
>db.articles.insert({
'text':
'Article content…‟,
'date' :
ISODate(...),
'title' :
‟Intro to MongoDB‟,
'author' : 'Dan Roberts‟,
'tags' :
[
'mongodb',
'database',
'nosql‟
]
});

11
Comparison Operators
$gt, $gte, $in, $lt, $lte, $ne, $nin
• Use to query documents
db.articles.find( { 'title' : ‟Intro to MongoDB‟ } )
db.articles.find( { ‟date' : { „$lt‟ :
{ISODate("2014-02-19T00:00:00.000Z") }} )
db.articles.find( { „tags‟ : { „$in‟ : [„nosql‟, „database‟] } } );

•

Logical: $or, $and, $not, $nor

•

Evaluation: $mod, $regex, $where Geospatial: $geoWithin, $geoIntersects, $near, $nearSphere

12

Element: $exists, $type
Cursors
• Find returns a cursor
– Use to iterate over the results
– cursor has many methods
>var cursor = db.articles.find (
{ ‟author' : ‟Dan Roberts‟ }
>cursor.hasNext()
true
>cursor.next()
{
'_id' :
ObjectId(...),
'text':
'Article content…‟,
'date' : ISODate(...),
'title' : ‟Intro to MongoDB‟,
'author' : 'Dan Roberts‟,
'tags' : [
'mongodb', 'database‟, 'nosql’
]
}
13

)
Projections
• Return only the attributes needed
– Boolean 0 or 1 syntax select attributes
– Improved efficiency

>var cursor = db.articles.find( { ‟author' : ‟Dan Roberts‟ } , {‘_id’:0, ‘title’:1})
>cursor.hasNext()
true
>cursor.next()
{ "title" : "Intro to MongoDB" }

14
Updates
Update Operators
$each, $slice, $sort, $inc, $push
$inc, $rename, $setOnInsert, $set, $unset, $max, $min
$, $addToSet, $pop, $pullAll, $pull, $pushAll, $push

$each, $slice, $sort
>db.articles.update(

{

{ '_id' : ObjectId(...)},
{ '$push' :
{'comments' : „Great
article!’ }
}
)

16

}

'text':
'Article content…‟
'date' :
ISODate(...),
'title' :
‟Intro to MongoDB‟,
'author' : 'Dan Roberts‟,
'tags' :
['mongodb',
'database‟,'nosql’ ],
’comments' :
[‘Great article!’ ]
Update Operators
Push to a fixed size array with…

$push, $each, $slice
{
>db.articles.update(

{ '_id' : ObjectId(...)},
{ '$push' : {'comments' :
{
'$each' : [„Excellent‟],
'$slice' : -3}},
})

17

}

'text':
'Article content…‟
'date' :
ISODate(...),
'title' :
‟Intro to MongoDB‟,
'author' : 'Dan Roberts‟,
'tags' :
['mongodb',
'database‟,'nosql’ ],
’comments' :
[‘Great
article!’, ‘More
please’, ‘Excellent’ ]
Update Operators - Bucketing
•

Push 10 comments to a document (bucket).

•

Automatically create a new document.

•

Use {upsert: true} instead of insert.
>db.comments.update(
{„c‟: {„$lt‟:10}},
{
„$inc‟ : {c:1},
'$push' : {
'comments' :
„Excellent‟
}
},
{ upsert : true }
)

18

{
„_id‟ : ObjectId( … )
„c‟ : 3,
’comments' :
[‘Great article!’,
‘More please’,
‘Excellent’ ]
}
Analytics – Pre-Aggregated reports
Interactions collections
METHOD

def add_interaction(article_id, type):

{
„_id‟ : ObjectId(..),
„article_id‟ : ObjectId(..),
„section‟ : „schema‟,
„date‟ : ISODate(..),
„daily‟: { „views‟ : 45,
„comments‟ : 150 }
„hours‟ : {
0:{
„views‟ : 10 },
1:{
„views‟ : 2 },
…
23 : { „views‟ : 14,
„comments‟ : 10 }
}

• Used for reporting on
articles
• Create “preaggregated” reports

}

19
Incrementing Counters
•

Use $inc to increment multiple counters.

•

Single Atomic operation.

•

Increment daily and hourly counters.

{

>db.interactions.update(
{„article_id‟ : ObjectId(..)},
{
„$inc‟ : {
„daily.views‟:1,
„daily.comments‟:1
„hours.8.views‟:1
„hours.8.comments‟:1
}
)

}

20

„_id‟ : ObjectId(..),
„article_id‟ : ObjectId(..),
„section‟ : „schema‟,
„date‟ : ISODate(..),
„daily‟: { „views‟ : 45,
„comments‟ : 150 }
„hours‟ : {
0:{
„views‟ : 10 },
1:{
„views‟ : 2 },
…
23 : { „views‟ : 14,
„comments‟ : 10 }
}
Incrementing Counters 2
• Increment new counters
{
„_id‟ : ObjectId(..),
„article_id‟ : ObjectId(..),
„section‟ : „schema‟,
„date‟ : ISODate(..),
„daily‟: { „views‟ : 45,
„comments‟ : 150 }
„hours‟ : {
…..
}
„referrers‟ : {
„google‟ : 27
}

>db.interactions.update(
{„article_id‟ : ObjectId(..)},
{
„$inc‟ : {
„daily.views‟:1,
„daily.comments‟:1,
„hours.8.views‟:1,

„hours.8.comments‟:1,
‘referrers.bing’ : 1
}
)

21

}
Incrementing Counters 2
• Increment new counters
{
„_id‟ : ObjectId(..),
„article_id‟ : ObjectId(..),
„section‟ : „schema‟,
„date‟ : ISODate(..),
„daily‟: { „views‟ : 45,
„comments‟ : 150 }
„hours‟ : {
…..
}
„referrers‟ : {
„google‟ : 27,
‘bing’ : 1
}

>db.interactions.update(
{„article_id‟ : ObjectId(..)},
{
„$inc‟ : {
„daily.views‟:1,
„daily.comments‟:1,
„hours.8.views‟:1,

„hours.8.comments‟:1,
‘referrers.bing’ : 1
}
)
}

22
Durability
Durability
•

With MongoDB you get to choose
•
•
•

•

Write Concerns
•
•

•

Report on success of write operations
getLastError called from driver

Trade off
•

24

In memory
On disk
Multiple servers

Latency of response
Unacknowledged

25
MongoDB Acknowledged
Default Write Concern

26
Wait for Journal Sync

27
Replica Sets
• Replica Set – two or more copies
• “Self-healing” shard
• Addresses many concerns:
- High Availability
- Disaster Recovery
- Maintenance

28
Wait for Replication

29
Summary
Summary
• Interacting with the database
– Queries and projections
– Inserts and Upserts
– Update Operators
– Bucketing
– Pre Aggregated reports
• basis for fast analytics

31
Next Session – 6th March
– Indexing
• Indexing strategies
• Tuning Queries

– Text Search
– Geo Spatial
– Query Profiler

32
Webinar: Build an Application Series - Session 3 - Interacting with the database

More Related Content

More from MongoDB

MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2MongoDB
 
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...MongoDB
 
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!MongoDB
 
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your MindsetMongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your MindsetMongoDB
 
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas JumpstartMongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas JumpstartMongoDB
 
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...MongoDB
 
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++MongoDB
 
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...MongoDB
 
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep DiveMongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep DiveMongoDB
 
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & GolangMongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & GolangMongoDB
 
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...MongoDB
 
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...MongoDB
 
MongoDB .local Paris 2020: Les bonnes pratiques pour sécuriser MongoDB
MongoDB .local Paris 2020: Les bonnes pratiques pour sécuriser MongoDBMongoDB .local Paris 2020: Les bonnes pratiques pour sécuriser MongoDB
MongoDB .local Paris 2020: Les bonnes pratiques pour sécuriser MongoDBMongoDB
 
MongoDB .local Paris 2020: Tout savoir sur le moteur de recherche Full Text S...
MongoDB .local Paris 2020: Tout savoir sur le moteur de recherche Full Text S...MongoDB .local Paris 2020: Tout savoir sur le moteur de recherche Full Text S...
MongoDB .local Paris 2020: Tout savoir sur le moteur de recherche Full Text S...MongoDB
 
MongoDB .local Paris 2020: Adéo @MongoDB : MongoDB Atlas & Leroy Merlin : et ...
MongoDB .local Paris 2020: Adéo @MongoDB : MongoDB Atlas & Leroy Merlin : et ...MongoDB .local Paris 2020: Adéo @MongoDB : MongoDB Atlas & Leroy Merlin : et ...
MongoDB .local Paris 2020: Adéo @MongoDB : MongoDB Atlas & Leroy Merlin : et ...MongoDB
 
MongoDB .local Paris 2020: Les bonnes pratiques pour travailler avec les donn...
MongoDB .local Paris 2020: Les bonnes pratiques pour travailler avec les donn...MongoDB .local Paris 2020: Les bonnes pratiques pour travailler avec les donn...
MongoDB .local Paris 2020: Les bonnes pratiques pour travailler avec les donn...MongoDB
 
MongoDB .local Paris 2020: Devenez explorateur de données avec MongoDB Charts
MongoDB .local Paris 2020: Devenez explorateur de données avec MongoDB ChartsMongoDB .local Paris 2020: Devenez explorateur de données avec MongoDB Charts
MongoDB .local Paris 2020: Devenez explorateur de données avec MongoDB ChartsMongoDB
 
MongoDB .local Paris 2020: La puissance du Pipeline d'Agrégation de MongoDB
MongoDB .local Paris 2020: La puissance du Pipeline d'Agrégation de MongoDBMongoDB .local Paris 2020: La puissance du Pipeline d'Agrégation de MongoDB
MongoDB .local Paris 2020: La puissance du Pipeline d'Agrégation de MongoDBMongoDB
 
MongoDB .local Toronto 2019: Keep your Business Safe and Scaling Holistically...
MongoDB .local Toronto 2019: Keep your Business Safe and Scaling Holistically...MongoDB .local Toronto 2019: Keep your Business Safe and Scaling Holistically...
MongoDB .local Toronto 2019: Keep your Business Safe and Scaling Holistically...MongoDB
 
MongoDB .local Toronto 2019: MongoDB – Powering the new age data demands
MongoDB .local Toronto 2019: MongoDB – Powering the new age data demandsMongoDB .local Toronto 2019: MongoDB – Powering the new age data demands
MongoDB .local Toronto 2019: MongoDB – Powering the new age data demandsMongoDB
 

More from MongoDB (20)

MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
 
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
 
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
 
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your MindsetMongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
 
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas JumpstartMongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
 
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
 
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
 
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
 
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep DiveMongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
 
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & GolangMongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
 
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
 
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
 
MongoDB .local Paris 2020: Les bonnes pratiques pour sécuriser MongoDB
MongoDB .local Paris 2020: Les bonnes pratiques pour sécuriser MongoDBMongoDB .local Paris 2020: Les bonnes pratiques pour sécuriser MongoDB
MongoDB .local Paris 2020: Les bonnes pratiques pour sécuriser MongoDB
 
MongoDB .local Paris 2020: Tout savoir sur le moteur de recherche Full Text S...
MongoDB .local Paris 2020: Tout savoir sur le moteur de recherche Full Text S...MongoDB .local Paris 2020: Tout savoir sur le moteur de recherche Full Text S...
MongoDB .local Paris 2020: Tout savoir sur le moteur de recherche Full Text S...
 
MongoDB .local Paris 2020: Adéo @MongoDB : MongoDB Atlas & Leroy Merlin : et ...
MongoDB .local Paris 2020: Adéo @MongoDB : MongoDB Atlas & Leroy Merlin : et ...MongoDB .local Paris 2020: Adéo @MongoDB : MongoDB Atlas & Leroy Merlin : et ...
MongoDB .local Paris 2020: Adéo @MongoDB : MongoDB Atlas & Leroy Merlin : et ...
 
MongoDB .local Paris 2020: Les bonnes pratiques pour travailler avec les donn...
MongoDB .local Paris 2020: Les bonnes pratiques pour travailler avec les donn...MongoDB .local Paris 2020: Les bonnes pratiques pour travailler avec les donn...
MongoDB .local Paris 2020: Les bonnes pratiques pour travailler avec les donn...
 
MongoDB .local Paris 2020: Devenez explorateur de données avec MongoDB Charts
MongoDB .local Paris 2020: Devenez explorateur de données avec MongoDB ChartsMongoDB .local Paris 2020: Devenez explorateur de données avec MongoDB Charts
MongoDB .local Paris 2020: Devenez explorateur de données avec MongoDB Charts
 
MongoDB .local Paris 2020: La puissance du Pipeline d'Agrégation de MongoDB
MongoDB .local Paris 2020: La puissance du Pipeline d'Agrégation de MongoDBMongoDB .local Paris 2020: La puissance du Pipeline d'Agrégation de MongoDB
MongoDB .local Paris 2020: La puissance du Pipeline d'Agrégation de MongoDB
 
MongoDB .local Toronto 2019: Keep your Business Safe and Scaling Holistically...
MongoDB .local Toronto 2019: Keep your Business Safe and Scaling Holistically...MongoDB .local Toronto 2019: Keep your Business Safe and Scaling Holistically...
MongoDB .local Toronto 2019: Keep your Business Safe and Scaling Holistically...
 
MongoDB .local Toronto 2019: MongoDB – Powering the new age data demands
MongoDB .local Toronto 2019: MongoDB – Powering the new age data demandsMongoDB .local Toronto 2019: MongoDB – Powering the new age data demands
MongoDB .local Toronto 2019: MongoDB – Powering the new age data demands
 

Recently uploaded

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 

Recently uploaded (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Webinar: Build an Application Series - Session 3 - Interacting with the database

  • 1. Application Development Series Back to Basics Interacting with the database Daniel Roberts @dmroberts #MongoDBBasics
  • 2. Agenda • Recap from last session • MongoDB Inserts & Queries – ObjectId – Returning documents – cursors – Projections • MongoDB Update operators – Fixed Buckets – Pre Aggregated Reports • Write Concern – Durability vs Performance trade off 2
  • 3. Q&A • Virtual Genius Bar – Use the chat to post questions – EMEA Solution Architecture / Support team are on hand – Make use of them during the sessions!!! 3
  • 4. Recap from last time….
  • 5. Architecture • Looked at the application architecture – JSON / RESTful – Python based HTTP(S) REST Client-side JSON Python web app (BSON) (eg AngularJS) Pymongo driver 5
  • 6. Schema and Architecture • Schema design – Modeled • • • • 6 Articles Comments Interactions Users
  • 7. Modeling Articles Articles collection def get_article(article_id) def get_articles(): def create_article(): METHODS { '_id' : 'text': • Posting articles • 'Article content…', 'date' : ISODate(...), insert 'title' : • Get List of articles • ObjectId(...), ‟Intro to MongoDB', 'author' : 'Dan Roberts', Return Cursor 'tags' : • Get individual article [ ] } 7 'mongodb', 'database', 'nosql‟
  • 8. Modeling Comments Comments collection METHODS def add_comment(article_id): def get_comments(article_id): { • Storing comments • Quickly retrieve most recent comments • Add new comments to document • „Bucketing‟ 8 „_id‟ : ObjectId(..), „article_id‟ : ObjectId(..), „page‟ : 1, „count‟ : 42 „comments‟ : [ { „text‟ : „A great article, helped me understand schema design‟, „date‟ : ISODate(..), „author‟ : „johnsmith‟ }, … }
  • 9. Modeling Interactions Interactions collection METHODS def add_interaction(article_id, type): { „_id‟ : ObjectId(..), „article_id‟ : ObjectId(..), „section‟ : „schema‟, „date‟ : ISODate(..), „daily‟: { „views‟ : 45, „comments‟ : 150 } „hours‟ : { 0:{ „views‟ : 10 }, 1:{ „views‟ : 2 }, … 23 : { „views‟ : 14, „comments‟ : 10 } } • Used for reporting on articles • Create “preaggregated” reports } 9
  • 11. Inserting documents • Driver generates ObjectId() for _id – if not specified – 12 bytes - 4-byte epoch, 3-byte machine id, a 2-byte process id, and a 3-byte counter. >db.articles.insert({ 'text': 'Article content…‟, 'date' : ISODate(...), 'title' : ‟Intro to MongoDB‟, 'author' : 'Dan Roberts‟, 'tags' : [ 'mongodb', 'database', 'nosql‟ ] }); 11
  • 12. Comparison Operators $gt, $gte, $in, $lt, $lte, $ne, $nin • Use to query documents db.articles.find( { 'title' : ‟Intro to MongoDB‟ } ) db.articles.find( { ‟date' : { „$lt‟ : {ISODate("2014-02-19T00:00:00.000Z") }} ) db.articles.find( { „tags‟ : { „$in‟ : [„nosql‟, „database‟] } } ); • Logical: $or, $and, $not, $nor • Evaluation: $mod, $regex, $where Geospatial: $geoWithin, $geoIntersects, $near, $nearSphere 12 Element: $exists, $type
  • 13. Cursors • Find returns a cursor – Use to iterate over the results – cursor has many methods >var cursor = db.articles.find ( { ‟author' : ‟Dan Roberts‟ } >cursor.hasNext() true >cursor.next() { '_id' : ObjectId(...), 'text': 'Article content…‟, 'date' : ISODate(...), 'title' : ‟Intro to MongoDB‟, 'author' : 'Dan Roberts‟, 'tags' : [ 'mongodb', 'database‟, 'nosql’ ] } 13 )
  • 14. Projections • Return only the attributes needed – Boolean 0 or 1 syntax select attributes – Improved efficiency >var cursor = db.articles.find( { ‟author' : ‟Dan Roberts‟ } , {‘_id’:0, ‘title’:1}) >cursor.hasNext() true >cursor.next() { "title" : "Intro to MongoDB" } 14
  • 16. Update Operators $each, $slice, $sort, $inc, $push $inc, $rename, $setOnInsert, $set, $unset, $max, $min $, $addToSet, $pop, $pullAll, $pull, $pushAll, $push $each, $slice, $sort >db.articles.update( { { '_id' : ObjectId(...)}, { '$push' : {'comments' : „Great article!’ } } ) 16 } 'text': 'Article content…‟ 'date' : ISODate(...), 'title' : ‟Intro to MongoDB‟, 'author' : 'Dan Roberts‟, 'tags' : ['mongodb', 'database‟,'nosql’ ], ’comments' : [‘Great article!’ ]
  • 17. Update Operators Push to a fixed size array with… $push, $each, $slice { >db.articles.update( { '_id' : ObjectId(...)}, { '$push' : {'comments' : { '$each' : [„Excellent‟], '$slice' : -3}}, }) 17 } 'text': 'Article content…‟ 'date' : ISODate(...), 'title' : ‟Intro to MongoDB‟, 'author' : 'Dan Roberts‟, 'tags' : ['mongodb', 'database‟,'nosql’ ], ’comments' : [‘Great article!’, ‘More please’, ‘Excellent’ ]
  • 18. Update Operators - Bucketing • Push 10 comments to a document (bucket). • Automatically create a new document. • Use {upsert: true} instead of insert. >db.comments.update( {„c‟: {„$lt‟:10}}, { „$inc‟ : {c:1}, '$push' : { 'comments' : „Excellent‟ } }, { upsert : true } ) 18 { „_id‟ : ObjectId( … ) „c‟ : 3, ’comments' : [‘Great article!’, ‘More please’, ‘Excellent’ ] }
  • 19. Analytics – Pre-Aggregated reports Interactions collections METHOD def add_interaction(article_id, type): { „_id‟ : ObjectId(..), „article_id‟ : ObjectId(..), „section‟ : „schema‟, „date‟ : ISODate(..), „daily‟: { „views‟ : 45, „comments‟ : 150 } „hours‟ : { 0:{ „views‟ : 10 }, 1:{ „views‟ : 2 }, … 23 : { „views‟ : 14, „comments‟ : 10 } } • Used for reporting on articles • Create “preaggregated” reports } 19
  • 20. Incrementing Counters • Use $inc to increment multiple counters. • Single Atomic operation. • Increment daily and hourly counters. { >db.interactions.update( {„article_id‟ : ObjectId(..)}, { „$inc‟ : { „daily.views‟:1, „daily.comments‟:1 „hours.8.views‟:1 „hours.8.comments‟:1 } ) } 20 „_id‟ : ObjectId(..), „article_id‟ : ObjectId(..), „section‟ : „schema‟, „date‟ : ISODate(..), „daily‟: { „views‟ : 45, „comments‟ : 150 } „hours‟ : { 0:{ „views‟ : 10 }, 1:{ „views‟ : 2 }, … 23 : { „views‟ : 14, „comments‟ : 10 } }
  • 21. Incrementing Counters 2 • Increment new counters { „_id‟ : ObjectId(..), „article_id‟ : ObjectId(..), „section‟ : „schema‟, „date‟ : ISODate(..), „daily‟: { „views‟ : 45, „comments‟ : 150 } „hours‟ : { ….. } „referrers‟ : { „google‟ : 27 } >db.interactions.update( {„article_id‟ : ObjectId(..)}, { „$inc‟ : { „daily.views‟:1, „daily.comments‟:1, „hours.8.views‟:1, „hours.8.comments‟:1, ‘referrers.bing’ : 1 } ) 21 }
  • 22. Incrementing Counters 2 • Increment new counters { „_id‟ : ObjectId(..), „article_id‟ : ObjectId(..), „section‟ : „schema‟, „date‟ : ISODate(..), „daily‟: { „views‟ : 45, „comments‟ : 150 } „hours‟ : { ….. } „referrers‟ : { „google‟ : 27, ‘bing’ : 1 } >db.interactions.update( {„article_id‟ : ObjectId(..)}, { „$inc‟ : { „daily.views‟:1, „daily.comments‟:1, „hours.8.views‟:1, „hours.8.comments‟:1, ‘referrers.bing’ : 1 } ) } 22
  • 24. Durability • With MongoDB you get to choose • • • • Write Concerns • • • Report on success of write operations getLastError called from driver Trade off • 24 In memory On disk Multiple servers Latency of response
  • 27. Wait for Journal Sync 27
  • 28. Replica Sets • Replica Set – two or more copies • “Self-healing” shard • Addresses many concerns: - High Availability - Disaster Recovery - Maintenance 28
  • 31. Summary • Interacting with the database – Queries and projections – Inserts and Upserts – Update Operators – Bucketing – Pre Aggregated reports • basis for fast analytics 31
  • 32. Next Session – 6th March – Indexing • Indexing strategies • Tuning Queries – Text Search – Geo Spatial – Query Profiler 32

Editor's Notes

  1. Not really fire and forget. This return arrow is to confirm that the network successfully transferred the packet(s) of data.This confirms that the TCP ACK response was received.
  2. Presenter should mention:Default is w:1w:majority is what most people should use for durability. Majority is a special token here signifying more than half of the nodes in the set have acknowledged the write.