SlideShare ist ein Scribd-Unternehmen logo
1 von 181
Downloaden Sie, um offline zu lesen
Mongo DB
06/06/2019 MongoDB class by Alexandre Bergere 1
{
Part One:[
Big Data
No SQL
],
Part Two:[
Mongo DB
Architecture & Modelization
CRUD
Replication
Security
Aggregation
Mongo DB Atlas
]
}
06/06/2019 MongoDB class by Alexandre Bergere 2
MongoDB class by Alexandre Bergere 3
alexandre.bergere@gmail.com
https://fr.linkedin.com/in/alexandrebergere
@AlexPhile
Avanade
2016 - 2019
Sr Anls, Data Engineering
Worked for 3 years as a senior analyst at
Avanade France, I have developed my skills
in data analysis (MSBI, Power BI, R, Python,
Spark, Cosmos DB) by working on innovative
projects and proofs of concept in the energy
industry.
ESAIP
Teacher
2016 - x
Data Freelance
2019 - x
06/06/2019 MongoDB class by Alexandre Bergere 4
Sources
A lot of the sources for making this courses provided from docs.mongodb.com or
https://www.university.mongodb.com.
BIG DATA
06/06/2019 MongoDB class by Alexandre Bergere 5
Data Source
Big Data Architecture
Data Ingestion & Processing Data Analytics Data Visualization
Data Storage
Data Lake / Data Warehouse
ETL
Messaging Queue
Data Management
Batch / Streaming
Machine Learning MOLAP Data Quality
No SQL
HDFS
SQL
Web Apps
Visualizations tools
Visuals Query
RDBMS
Social Media
Device
IoT / Sensors
Files (log, Unst)
06/06/2019 MongoDB class by Alexandre Bergere 6
Object store
Data Storage
Relational data store HDFS Key Value data store Columnar data store
Object store Search data store Graph data store Document data store
06/06/2019 MongoDB class by Alexandre Bergere 7
NO SQL
06/06/2019 MongoDB class by Alexandre Bergere 8
Data management
NoSQL
OLAP
System R & SQL
Cobol
Hierarchic model
06/06/2019 MongoDB class by Alexandre Bergere 9
70’s
80’s
90’s
20th
NoSQL
OLAP
System R & SQL
Cobol
Hierarchic model
Codd's 12 Rules
o Rule 1: Information Rule
o Rule 2: Guaranteed Access Rule
o Rule 3: Systematic Treatment of NULL Values
o Rule 4: Active Online Catalog
o Rule 5: Comprehensive Data Sub-Language Rule
o Rule 6: View Updating Rule
o Rule 7: High-Level Insert, Update, and Delete Rule
o Rule 8: Physical Data Independence
o Rule 9: Logical Data Independence
o Rule 10: Integrity Independence
o Rule 11: Distribution Independence
o Rule 12: Non-Subversion Rule
Data management
RDBMS
06/06/2019 MongoDB class by Alexandre Bergere 10
NoSQL
OLAP
System R & SQL
Cobol
Hierarchic model
Data management
OLAP : Online Analytical Processing
06/06/2019 MongoDB class by Alexandre Bergere 11
Data management
No SQL
NoSQL
OLAP
System R & SQL
Cobol
Hierarchic model
Benefits:
o performance
o volume
o variety
06/06/2019 MongoDB class by Alexandre Bergere 12
Different type of data storage:
o Key-value
o Document data store
o Columnar data store
o Graph data store
o Search data store
MongoDB
06/06/2019 MongoDB class by Alexandre Bergere 13
Created in 2007 & first release
in 2010.
Easy and simple … as a leaf.
Document data store &
Schemaless.
06/06/2019 MongoDB class by Alexandre Bergere 14
Nexus Architecture
06/06/2019 MongoDB class by Alexandre Bergere 15
Drivers & Frameworks
06/06/2019 MongoDB class by Alexandre Bergere 16
Mongo DB is easy
For many developers, data model goes hand in hand with object mapping, and for that purpose
you may have used an object-relational mapping library, such as Java’s Hibernate framework or
Ruby’s ActiveRecord.
Such libraries can be useful for efficiently building applications with a RDBMS, but they’re less
necessary with MongoDB. This is due in part to the fact that a document is already an object-
like representation. It’s also partly due to the MongoDB drivers, which already provide a fairly
high-level interface to MongoDB. Without question, you can build applications on MongoDB
using the driver interface alone.
06/06/2019 MongoDB class by Alexandre Bergere 17
Use cases
o Web application (mongoDB is well-suited as primary datastore for web application)
o Agile development
o Analytics and logging
o Caching
o Variable Schemas
06/06/2019 MongoDB class by Alexandre Bergere 18
The case for adding NoSQL
o Large volumes of rapidly changing structured, semi-structured, and unstructured data
o Agile sprints, quick schema iteration, and frequent code pushes
o API-driven, object-oriented programming that is easy to use and flexible
o Geographically distributed scale-out architecture instead of expensive, monolithic
architecture
Consider, for example, enterprise resource planning (ERP), a standard for relational databases.
What if you want to offer ERP forms users can actually modify if they need to? A document-
based NoSQL database such as MongoDB can provide that functionality without requiring you
to rebuild your whole data schema every time a user wants to change the data format.
06/06/2019 MongoDB class by Alexandre Bergere 19
Mongo DB history
06/06/2019 MongoDB class by Alexandre Bergere 20
Mongo DB 4.0 : ACID transactions
More info.
06/06/2019 MongoDB class by Alexandre Bergere 21
Leader in The Forrester Wave™: Big Data NoSQL, Q1 2019
o “MongoDB remains the most popular
NoSQL database”
o Used by more than 8,000 companies,
including many Fortune 100
companies.
o Highest possible scores in 21 of the
26 criteria.
06/06/2019 MongoDB class by Alexandre Bergere 22
Companies
06/06/2019 MongoDB class by Alexandre Bergere 23
White papers
MongoDB – BI &
Analytics
MongoDB – Kafka MongoDB – Spark
06/06/2019 MongoDB class by Alexandre Bergere 24
Modelization
06/06/2019 MongoDB class by Alexandre Bergere 25
Document are rich data structure
• JSON:
• String, Number, Array, Object, NULL, Boolean.
• BSON:
• Date, BinData, ObjectID, Geo-Location.
• Better storage performance.
ObjectID:
◦ _id : 'DATE[4] | MAC_ADDR[3] | PID[2] | COUNTER[3]
06/06/2019 MongoDB class by Alexandre Bergere 26
Available Types
Type Number Alias Notes
Double 1 “double”
String 2 “string”
Object 3 “object”
Array 4 “array”
Binary data 5 “binData”
Undefined 6 “undefined” Deprecated.
ObjectId 7 “objectId”
Boolean 8 “bool”
Date 9 “date”
Null 10 “null”
RegularExpression 11 “regex”
DBPointer 12 “dbPointer” Deprecated.
JavaScript 13 “javascript”
Symbol 14 “symbol” Deprecated.
JavaScript (with scope) 15 “javascriptWithScope”
32-bit integer 16 “int”
Timestamp 17 “timestamp”
64-bit integer 18 “long”
Decimal128 19 “decimal” New in version 3.4.
Min key -1 “minKey”
Max key 127 “maxKey”
06/06/2019 MongoDB class by Alexandre Bergere 27
Documents are Flexible
06/06/2019 MongoDB class by Alexandre Bergere 28
Document Model
Pers_ID Surname First_Name City
0 Miller Paul London
1 Ortega Alvaro Valencia
2 Huber Urs Zurich
3 Blanc Gaston Paris
4 Bertolini Fabrizio Rome
Car_ID Model Year Value Pers_ID
101 Bently 1973 100000 0
102 Rolls Royce 1965 330000 0
103 Peugot 1993 500 3
104 Ferrari 2005 150000 4
105 Renault 1998 2000 3
106 Renault 2001 7000 3
107 Smart 1999 2000 2
CAR
PERSON
Mongo DB
RDBMS
06/06/2019 MongoDB class by Alexandre Bergere 29
TP - Modelization
1. Transform this address « 125 avenue de la république, 75011, PARIS » in BSON object.
2. Transform this 2 addresses « 125 avenue de la république, 75011, PARIS » and « 34 rue Ferdinand,
75012, PARIS » in an array.
3. Transform the schema below on BSON document.
ID LastName FirstName Age
1 BERGERE Alexandre 26
Address ID People
125 avenue de la république, 75011,
PARIS
1
34 rue Ferdinand,
75012, PARIS
1
1 n
06/06/2019 MongoDB class by Alexandre Bergere 30
MongoDB - Starter
06/06/2019 MongoDB class by Alexandre Bergere 31
SQL vs MongoDB Terms
SQL Terms/Concepts MongoDB Terms/Concepts
Database Database
Table Collection
Line Document
Column Field
Index Index
Join Embeded or linked document
Primary key Primary key (start by « _id »)
06/06/2019 MongoDB class by Alexandre Bergere 32
Storage
o MMAPv1
o WiredTiger
o In Memory
06/06/2019 MongoDB class by Alexandre Bergere 33
Installation
06/06/2019 MongoDB class by Alexandre Bergere 34
Launch instance
Launch as a service:
o mongod --dbpath C:UsersalexaDocumentsMongoDBdata -- logpath
C:UsersalexaDocumentMongoDBlogs.log
Launch the conection:
o mongo
Launch a shard:
o mongos
Original Shortcut
--db -d
--collection -c
--username -u
--password -p
--host -h
Options:
06/06/2019 MongoDB class by Alexandre Bergere 35
The Javascript console
var authColl = db.getCollection("auth")
authColl.insertOne(
{
usrName : "John Doe",
usrDept : "Sales",
usrTitle : "Executive Account Manager",
authLevel : 4,
authDept : [ "Sales", "Customers"]
}
)
06/06/2019 MongoDB class by Alexandre Bergere 36
DML
06/06/2019 MongoDB class by Alexandre Bergere 37
DML
# Returns all database
> show dbs
# The current database name:
> db.getName()
# Returns all database
> show dbs
# Returns all collection in the current database:
> db.getCollectionNames()
# Returns a collection or a view object:
> db.getCollection(name)
# The current database connection:
> db.getMongo()
# Clean the console log:
> cls
# Return collection informations:
> db.getCollectionInfos({name: "name"})
06/06/2019 MongoDB class by Alexandre Bergere 38
DML
# Removes the current database:
> db.dropDatabase()
# Copies a database to another database on the current host:
>db.copyDatabase(fromdb, todb, fromhost, usern
ame, password, mechanism)
# Copies a database from a remote host to the current host:
> db.cloneDatabase("hostname")
# Rename collection:
> db.renameCollection({ renameCollection:
"fromCollection", to: " toCollection" })
> use test
Or
> db.orders.renameCollection( "toCollection" )
# Copies data directly between MongoDB instances:
> db.cloneCollection(from, collection, query)
06/06/2019 MongoDB class by Alexandre Bergere 39
Stats
# Returns statistics that reflect the use state of a single database or
collection.
> db.stats()
> db.collection.stats()
{
"ns" : "guidebook.restaurants",
"count" : 25359,
"size" : 10630398,
"avgObjSize" : 419,
"storageSize" : 4104192
"capped" : false,
"wiredTiger" : {
"metadata" : {
"formatVersion" : 1
}, […]
"nindexes" : 4,
"totalIndexSize" : 626688,
"indexSizes" : {
"_id_" : 217088,
"borough_1_cuisine_1" : 139264,
"cuisine_1" : 131072,
"borough_1_address.zipcode_1" :
139264
}
06/06/2019 MongoDB class by Alexandre Bergere 40
Command-line tools
Launch in the shell, not in mongoDB instance.
06/06/2019 MongoDB class by Alexandre Bergere 41
Import or export document
mongoexport and mongoimport: Export and import JSON, CSV, and TSV7 data.
# Import multiples document:
mongoimport -d crunchbase -c companies
C:UsersalexaDocumentsMongoDBsrccompanies.json
# Import multiples document in an array:
mongoimport -d crunchbase -c artists --file
C:UsersalexaDocumentsMongoDBsrcartists.json --jsonArray
# Export collection:
mongoexport --db crunchbase --collection artists --out artists.json
06/06/2019 MongoDB class by Alexandre Bergere 42
Backup
mongodump
mongodump
--host
--port
--db
--username
--password (when specifying the password as part of the URI connection string)
--authenticationDatabase
--authenticationMechanism
# mongodump a Collection:
mongodump --db test --collection collection
# mongodump a Database:
mongodump –archive=test.20100224.archive –db Crunchbase
06/06/2019 MongoDB class by Alexandre Bergere 43
Restore
mongostore
mongostore
--host
--port
--collection /pwd –db /pwd
--db /pwd
--username
--password
--authenticationDatabase
<path to the backup>
# Output an Archive to Standard Output:
mongodump --archive --db test --port 27017 | mongorestore --archive --port 27018
06/06/2019 MongoDB class by Alexandre Bergere 44
Others
mongostore
o mongosniff: A wire-sniffing tool for viewing operations sent to the database. It essentially
translates the BSON going over the wire to human-readable shell statements.
o mongostat: Similar to iostat, this utility constantly polls MongoDB and the system to provide
helpful stats, including the number of operations per second (inserts, queries, updates, deletes,
and so on), the amount of virtual memory allocated, and the number of connections to the
server.
o mongotop: Similar to top, this utility polls MongoDB and shows the amount of time it spends
reading and writing data in each collection.
o mongoperf: Helps you understand the disk operations happening in a running MongoDB
instance.
o mongooplog: Shows what’s happening in the MongoDB oplog.
o Bsondump: Converts BSON files into human-readable formats including JSON.
06/06/2019 MongoDB class by Alexandre Bergere 45
CRUD
06/06/2019 MongoDB class by Alexandre Bergere 46
> create
# Create a database
> {
create: <collection or view name>,
capped: <true|false>,
autoIndexId: <true|false>,
size: <max_size>,
max: <max_documents>,
flags: <0|1|2|3>,
storageEngine: <document>,
validator: <document>,
validationLevel: <string>,
validationAction: <string>,
indexOptionDefaults: <document>,
viewOn: <source>,
pipeline: <pipeline>,
collation: <document>
}
06/06/2019 MongoDB class by Alexandre Bergere 47
Capped collection
Distinguished from standard collectionsby their fixed size. This means that once a capped
collection reaches its maximum size, subsequent inserts will overwrite the least-recently-
inserted documents in the collection.
This design prevents users from having to prune the collection manually when only recent data
may be of value.
> {
create: <collection or view name>,
capped: <true|false>
[…]
}
Designed for high-performance logging scenarios.
06/06/2019 MongoDB class by Alexandre Bergere 48
> find
# FIND()
> db.<collection>.find ({<conditions>},{<champs>})
> db.products.find( { qty: { $gt: 25 } }, { item: 1, qty: 1 } )
sort, first, skip, second, and limit last because that is the
only order that makes sense.
# Options:
>
.pretty()
.sort() : 1 : ASC, -1: DESC :
sort({‘name’:-1})
.skip() : number
.limit() : number
.count()
06/06/2019 MongoDB class by Alexandre Bergere 49
Partial Match Queries in Users
# Use regular expression:
> db.users.find({'last_name': /^Ber/})
06/06/2019 MongoDB class by Alexandre Bergere 50
> insert
# INSERT()
> db.<collection>.insert ({<value>})
> db.<collection>.insertMany([{<values>}])
> db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom:
"cm" } },
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85,
uom: "cm" } }
])
db.collection.insertOne() Inserts a single document into a collection.
db.collection.insertMany() db.collection.insertMany() inserts multiple documents into a collection.
db.collection.insert()
db.collection.insert() inserts a single document or multiple documents into
a collection.
06/06/2019 MongoDB class by Alexandre Bergere 51
> update
# UPDATE()
> db.<collection>.update
({<conditions>},{<champs>},{upsert:true/false},{multi:true/false}
)
> { "_id": "artist:281", "last_name": "Cotillard", "first_name": "Marion", "birth_date": "1975" }
# Operator Update:
> db.artists.update({"_id": "artist:281"},{ $set : {"last_name" : "Page"}})
> { "_id": "artist:281", "last_name": “Page", "first_name": "Marion", "birth_date": "1975" }
# Replacement Update:
> db.artists.update({"_id": "artist:281"},{"last_name" : "Page"})
> { "_id": "artist:281", "last_name": “Page"} ❑ Operator Update
❑ Replacement Update
All updates require at least two arguments. The first specifies which documents to update, and
the second defines how the selected documents should be modified
06/06/2019 MongoDB class by Alexandre Bergere 52
> update
Upsert: boolean Optional. If set to true, creates a new document when no document
matches the query criteria. The default value is false, which does not insert a new document
when no match is found.
Multi: boolean Optional. If set to true, updates multiple documents that meet the query
criteria. If set to false, updates one document. The default value is false.
# UPDATE()
> db.<collection>.update ({<conditions>},{<champs>}
,{upsert:true/false}
,{multi:true/false}
)
> db.pageview.update({'_id':'/potager/users'},{$inc:{'views':1}},{upsert:true})
06/06/2019 MongoDB class by Alexandre Bergere 53
Query Operator
Name Description
$eq Matches values that are equal to a specified value.
$gt Matches values that are greater than a specified value.
$gte Matches values that are greater than or equal to a specified value.
$lt Matches values that are less than a specified value.
$lte Matches values that are less than or equal to a specified value.
$ne Matches all values that are not equal to a specified value.
$in Matches any of the values specified in an array.
06/06/2019 MongoDB class by Alexandre Bergere 54
Query Operator
Name Description
$set Sets the value of a field in a document.
$unset Removes the specified field from a document.
$inc Increments a field by a specified value.
$rename updates the name of a field
$muc Multiply the value of a field by a number
> db.products.update( { _id: "56c0befa5e435acc1d4a5fbd"}, { $inc: { quantity: -2}
})
06/06/2019 MongoDB class by Alexandre Bergere 55
Query Operator : $set
# $set
> db.products.update(
{ _id: 100 },
{ $set:
{
quantity: 500,
details: { model: "14Q3", make: "xyz" },
tags: [ "coats", "outerwear", "clothing" ]
}
}
)
# $set Embedded Documents
> db.products.update(
{ _id: 100 },
{ $set: { "details.make": "zzz" } }
)
# $set in Arrays
> db.products.update(
{ _id: 100 },
{ $set:
{
"tags.1": "rain gear",
"ratings.0.rating": 2
}
}
)
06/06/2019 MongoDB class by Alexandre Bergere 56
Array
{
_id: 1,
fruits: [ "apples", "pears", "oranges", "grapes", "bananas" ],
vegetables: [ "carrots", "celery", "squash", "carrots" ]
}
{
_id: 2,
fruits: [ "plums", "kiwis", "oranges", "bananas", "apples" ],
vegetables: [ "broccoli", "zucchini", "carrots", "onions" ]
}
> db.stores.update(
{ },
{ $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
{ multi: true }
)
06/06/2019 MongoDB class by Alexandre Bergere 57
Query Operator : Arrays
Name Description
$set Sets the value of a field in a document.
$unset Removes the specified field from a document.
$inc Increments a field by a specified value.
$rename updates the name of a field
$muc Multiply the value of a field by a number
> db.products.update( { _id: "56c0befa5e435acc1d4a5fbd"}, { $inc: { quantity: -2}
})
06/06/2019 MongoDB class by Alexandre Bergere 58
> delete
# DELETE()
> db.<collection>.remove ({<conditions>})
> db.artists.remove({"_id": "artist:39"})
# Remove all fields
> db.artists.remove({})
06/06/2019 MongoDB class by Alexandre Bergere 59
TP - Modelization
1. Import the json document “veg_garden” into
mongoDB.
2. Return all vegetable garden with an existing
property of “number”.
3. Return all vegetable garden with an existing
property of “harvest”.
4. Return all vegetable garden with a service’ title
“Classes”.
5. Return all vegetable garden with a sale’s address
number 52.
6. Return all vegetable garden that have the product
97.
7. Import json documents “companies” and “artists”
into mongoDB.
8. Return the number of companies with a number
of employees less or equal to 45.
9. Return artists from the 6th to the 9th ordered desc
by their name.
10. Insert the following artist:
"_id": "artist:9", "last_name": "Bergere",
"first_name": "Alexandre", "birth_date": "1992“.
11. Add « golf » on artist’s hobbies with the id 280.
12. Add « yoga » on artist’s hobbies with the id 282.
13. Delete hobbies « pony » and « painting » from the
artist 280.
06/06/2019 MongoDB class by Alexandre Bergere 60
TP - Modelization
# 1. Import the json document “veg_garden” into mongoDB.
mongoimport -d crunchbase -c vegGarden --file C:UsersalexCoursMongoDB2018-2019srcveg_garden.json --
jsonArray
# 2. Return all vegetable garden with an existing property of “number”.
> db.vegGarden.find({"number":{$exists:true}}).pretty()
# 3. Return all vegetable garden with an existing property of “harvest”.
> db.vegGarden.find({"harvest":{$exists:true}}).pretty()
# 4. Return all vegetable garden with a service’s title “Classes”.
> db.vegGarden.find({"service.title":“Classes"}).pretty()
# 5. Return all vegetable garden with a sale’s address number 52.
> db.vegGarden.find({"adresse.sale.num":52}).pretty()
# 6. Delete hobbies « pony » and « painting » from the artist 280.
> db.vegGarden.find({"products":{$in:[97]}})
06/06/2019 MongoDB class by Alexandre Bergere 61
TP - Modelization
# 7. Import json documents “companies” and “artists” into mongoDB.
mongoimport -d crunchbase -c artists --file C:UsersalexCoursMongoDB2018-2019srcartists.json --
jsonArray
mongoimport -d crunchbase -c companies C:UsersalexCoursMongoDB2018-2019srccompanies.json
# 8. Return the number of companies with a number of employees less or equal to 45.
> db.companies.count({number_of_employees:{$lte:45}})
# 9. Return artists from the 6th to the 9th ordered desc by their name
> db.artists.find().pretty().sort({"last_name":-1}).skip(5).limit(4)
# 10. Insert the following artist:
"_id": "artist:9", "last_name": "Bergere", "first_name": "Alexandre", "birth_date": "1992" .
Remplacer le numéro d’id par 282.
> db.artists.insert({ "_id": "artist:9", "last_name": "Bergere", "first_name": "Alexandre", "birth_date":
"1992" })
# 11. Add « golf » on artist’s hobbies with the id 280.
> db.artists.update({"_id": "artist:280"},{$push:{"hobbies":"golf"}})
# 12. Add « yoga » on artist’s hobbies with the id 282.
> db.artists.update({"_id": "artist:282"},{$push:{"hobbies":"yoga"}})
# 13. Retirer les hobbies « poney » et « photo » à l’artiste 280.
> db.artists.update({"_id": "artist:280"},{$pull:{"hobbies": {$in:["pony","photo"]}}})
06/06/2019 MongoDB class by Alexandre Bergere 62
Schema Validation
06/06/2019 MongoDB class by Alexandre Bergere 63
Schema validation
• Implement data governance without sacrificing
the agility that comes from a dynamic schema.
• With schema validation, developers and
operations spend less time defining data
quality controls in their applications, and
instead delegate these tasks to the database.
To specify validation rules when creating a new collection, use with the valid
db.createCollection() option.
To add document validation to an existing collection, use collMod command with the validator
option.
06/06/2019 MongoDB class by Alexandre Bergere 64
Example of schema validation
# Create a database
> db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "name", "year", "major", "gpa" ],
additionalProperties: true,
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
gender: {
bsonType: "string",
description: "must be a string and is not required"
},
year: {
bsonType: "int",
minimum: 2017,
maximum: 3017,
exclusiveMaximum: false,
description: "must be an integer in [ 2017, 3017 ]
and is required"
}
> […] major: {
enum: [ "Math", "English",
"Computer Science", "History", null ],
description: "can only be
one of the enum values and is required"
},
gpa: {
bsonType: [ "double" ],
minimum: 0,
description: "must be a
double and is required"
}
}
}
}
})
06/06/2019 MongoDB class by Alexandre Bergere 65
Query expression
In addition to JSON Schema validation, MongoDB supports validation with query filter
expressions using the query operators, with the exception of $near, $nearSphere, $text, and
$where.
> db.createCollection( "contacts",
{ validator: { $or:
[
{ phone: { $type: "string" } },
{ email: { $regex: /@mongodb.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
}
} )
06/06/2019 MongoDB class by Alexandre Bergere 66
Add a validator to an existing collection
In addition to JSON Schema validation, MongoDB supports validation with query filter
expressions using the query operators, with the exception of $near, $nearSphere, $text, and
$where.
> db.runCommand( {
collMod: "contacts",
validator: { $jsonSchema: {
bsonType: "object",
required: [ "phone", "name" ],
properties: {
phone: {
bsonType: "string",
description: "must be a string and is required"
},
name: {
bsonType: "string",
description: "must be a string and is required"
}
}
} },
validationLevel: "moderate"
} )
collMod
06/06/2019 MongoDB class by Alexandre Bergere 67
Validation level & action
ValidationLevel Description
"off" disable validation entirely.
"strict"
If the validationLevel is strict (the default), MongoDB
applies validation rules to all inserts and updates.
"moderate"
If the validationLevel is moderate, MongoDB applies
validation rules to inserts and to updates to existing
documents that already fulfil the validation criteria. With
the moderate level, updates to existing documents that do
not fulfill the validation criteria are not checked for
validity.
validationAction Description
"error"
Default Documents must pass validation before the write
occurs. Otherwise, the write operation fails.
"warn"
Documents do not have to pass validation. If the document
fails validation, the write operation logs the validation
failure.
ValidationLevel option, which determines how strictly MongoDB
applies validation rules to existing documents during an update.
ValidationAction option, which determines whether MongoDB
should error and reject documents that violate the validation rules or
warn about the violations in the log but allow invalid documents.
06/06/2019 MongoDB class by Alexandre Bergere 68
Bypass Document Validation
Users can bypass document validation on commands and methods that support the
bypassDocumentValidation option. The following commands and their equivalent methods
support bypassing document validation:
oaggregate
oapplyOps
ocloneCollection on the destination collection
oclone on the destination
ocopydb on the destination
ofindAndModify
oinsert
omapReduce
oUpdate
For deployments that have enabled access control, to bypass document validation, the
authenticated user must have bypassDocumentValidation action. The built-in roles dbAdmin
and restore provide this action.
06/06/2019 MongoDB class by Alexandre Bergere 69
TP – Schema Validation
1. Add the following schema validation to the artists’ collection:
• "last_name","first_name","status" required.
• “status” can take only this two values: "alive“ or "dead"
2. Try to insert the following artist: { "last_name": "Katerine", "first_name": "Philippe"}
3. Update the artist with the id “artists:281”, by modify his name by “Kheirona”.
4. Change validation level in « moderate ».
5. Try again the update in question 3.
6. Change validation action in « warn », then insert again the artist in question 2.
06/06/2019 MongoDB class by Alexandre Bergere 70
TP – Schema Validation
# 1. Add the following schema validation to the artists’ collection:
> db.runCommand({
collMod: "artists",
validator:{ $jsonSchema:{
bsonType: "object",
required:["last_name","first_name","status"],
properties:{
last_name:{
bsonType: "string",
description:"must be a string and is required"
}
,first_name:{
bsonType: "string",
description:"must be a string and is required"
}
,status:{
enum: ["alive", "dead"],
description:"must be a alive or dead and is required"
}
}
},
}
,validationLevel: "strict"
})
06/06/2019 MongoDB class by Alexandre Bergere 71
TP – Schema Validation
# 1. Option 2:
> db.runCommand({
collMod: "artists",
validator:{
$and:
[
{ last_name: { $type: "string" } },
{ first_name: { $type: "string" } },
{ status: { $in: [ "alive", "dead" ] } }
],
$jsonSchema:{
required:["last_name","first_name","status"]
},
}
,validationLevel: "strict"
})
06/06/2019 MongoDB class by Alexandre Bergere 72
TP – Schema Validation
# 2. Try to insert the following artist: { "last_name": "Katerine", "first_name":
"Philippe"}
> db.artists.insert({ "last_name": "Katerine", "first_name": "Philippe"}) –
{failed}
# 3. Update the artist with the id “artists:281”, by modify his name by
“Kheirona”.
> db.artists.update({"_id": "artist:281"},{ $set:{ "last_name": " Kheirona" }})
# 4. Change validation level in « moderate ».
> db.runCommand({
collMod: "artists"
,validationLevel : "moderate"
})
# 6. Change validation action in « warn », then insert again the artist in question
2.
db.runCommand({
collMod: "artists"
,validationAction: "warn"
})
2018-12-01T12:31:23.738-0500 W STORAGE [conn1] Document would fail validation collection: example.contacts2 doc: { _id:
ObjectId('5a2191ebacbbfc2bdc4dcffc’), last_name: " Kheirona "}
06/06/2019 MongoDB class by Alexandre Bergere 73
One to many
06/06/2019 MongoDB class by Alexandre Bergere 74
One to N
One to few
06/06/2019 MongoDB class by Alexandre Bergere 75
One to N
One to many
06/06/2019 MongoDB class by Alexandre Bergere 76
One to N
{
_id: ObjectId("6a5b1476238d3b4dd5000048"),
slug: "gardening-tools",
name: "Gardening Tools",
description: "Gardening gadgets galore!",
parent_id: ObjectId("55804822812cb336b78728f9"),
ancestors: [
{
name: "Home",
_id: ObjectId("558048f0812cb336b78728fa"),
slug: "home"
},
{
name: "Outdoors",
_id: ObjectId("55804822812cb336b78728f9"),
slug: "outdoors"
}
]
}
> db.products.find({category_ids:
ObjectId('6a5b1476238d3b4dd5000048')})
06/06/2019 MongoDB class by Alexandre Bergere 77
One to N
{
_id: ObjectId("6a5b1476238d3b4dd5000048"),
slug: "gardening-tools",
name: "Gardening Tools",
description: "Gardening gadgets galore!",
parent_id: ObjectId("55804822812cb336b78728f9"),
ancestors: [
{
name: "Home",
_id: ObjectId("558048f0812cb336b78728fa"),
slug: "home"
},
{
name: "Outdoors",
_id: ObjectId("55804822812cb336b78728f9"),
slug: "outdoors"
}
]
}
# $set in Arrays
> db.products.find({category_ids:
ObjectId('6a5b1476238d3b4dd5000048')})
# To query for all categories from a given product:
> var product = db.products.findOne({"slug":
"wheelbarrow-9092"})
> db.categories.find({_id: {$in:
product['category_ids']}})
06/06/2019 MongoDB class by Alexandre Bergere 78
TP – One to Many
Student Subject
06/06/2019 MongoDB class by Alexandre Bergere 79
TP – One to Many
# Student:
> db.student.insertMany([
{
"name":"bergere",
"surname":"alex",
"subject":[
{
"id_ subject": "MongoDB"
,"note" : [15,13]
},
{
"id_subject": "NodeJS"
,"note" : [12,13]
}
]
},
{
"name":"Fauchard",
"surname":"Than Tuan",
"subject":[
{
"id_ subject": "MongoDB"
,"note" : [12,18]
},
{
"id_subject": "NodeJS"
,"note" : [15,8]
}
]
}
])
06/06/2019 MongoDB class by Alexandre Bergere 80
TP – One to Many
# Subject:
> db.subject.insertMany([
{
"_id":"MongoDB"
,"nom":"MongoDB"
,"salle":"A09"
,"prof":"Alexandre Bergere"
},
{
"_id":"NodeJS"
,"nom":"NodeJS"
,"salle":"A12"
,"prof":"Thierry Dupont"
}
])
06/06/2019 MongoDB class by Alexandre Bergere 81
TP – One to Many
# Request:
> var subject = []
> db.subject.find().forEach(function(u) { subject.push(u._id) })
> db.student.find({"subject.id_ subject": {$in: subject}})
06/06/2019 MongoDB class by Alexandre Bergere 82
TP – Many to Many
Student Subject
06/06/2019 MongoDB class by Alexandre Bergere 83
TP – Many to Many
# Student:
> db.student.insertMany([
{
"_Id" : ObjectID("23109834091209"),
"name":"bergere",
"surname":"alex",
"subject":[
{
"id_ subject": "MongoDB"
,"note" : [15,13]
},
{
"id_subject": "NodeJS"
,"note" : [12,13]
}
]
},
{
"_Id" : ObjectID("97099230912812"),
"name":"Fauchard",
"surname":"Than Tuan",
"subject":[
{
"id_ subject": "MongoDB"
,"note" : [12,18]
},
{
"id_subject": "NodeJS"
,"note" : [15,8]
}
]
}
06/06/2019 MongoDB class by Alexandre Bergere 84
TP – Many to Many
# Subject:
> db.subject.insertMany([
{
"_id":"MongoDB"
,"nom":"MongoDB"
,"salle":"A09"
,"prof":"Alexandre Bergere"
,"Students":[
{
"Prom":"ir2016",
"Student_id":[ObjectID("97099230912812"),
ObjectID("23109834091209")]
}
]
},
{
"_id":"NodeJS"
,"nom":"NodeJS"
,"salle":"A12"
,"prof":"Thierry Dupont"
,"Students":[
{
"Prom":"ir2016",
"Student_id":[ObjectID("97099230912812"),
ObjectID("23109834091209")]
}
]
}
])
06/06/2019 MongoDB class by Alexandre Bergere 85
$lookup
> {
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
as: <output array field>
}
}
06/06/2019 MongoDB class by Alexandre Bergere 86
$lookup
db.orders.insert([
{ "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 },
{ "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 },
{ "_id" : 3 }
])
db.inventory.insert([
{ "_id" : 1, "sku" : "almonds", description: "product 1", "instock" : 120 },
{ "_id" : 2, "sku" : "bread", description: "product 2", "instock" : 80 },
{ "_id" : 3, "sku" : "cashews", description: "product 3", "instock" : 60 },
{ "_id" : 4, "sku" : "pecans", description: "product 4", "instock" : 70 },
{ "_id" : 5, "sku": null, description: "Incomplete" },
{ "_id" : 6 }
])
06/06/2019 MongoDB class by Alexandre Bergere 87
$lookup
> db.orders.aggregate([
{
$lookup:
{
from: "inventory",
localField: "item",
foreignField: "sku",
as: "inventory_docs"
}
}
])
{
"_id" : 1,
"item" : "almonds",
"price" : 12,
"quantity" : 2,
"inventory_docs" : [
{ "_id" : 1, "sku" : "almonds", "description" : "product 1", "instock" :
120 }
]
}
{
"_id" : 2,
"item" : "pecans",
"price" : 20,
"quantity" : 1,
"inventory_docs" : [
{ "_id" : 4, "sku" : "pecans", "description" : "product 4", "instock" :
70 }
]
}
{
"_id" : 3,
"inventory_docs" : [
{ "_id" : 5, "sku" : null, "description" : "Incomplete" },
{ "_id" : 6 }
]
}06/06/2019 MongoDB class by Alexandre Bergere 88
TP – $lookup
# Subject:
> db.subject.aggregate([
{
$lookup:
{
from: "student",
localField: "_id",
foreignField: "subject.id_
subject",
as: "student"
}
}
])
# Student:
> db.student.aggregate([
{
$lookup:
{
from: "subject",
localField: "subject.id_
subject",
foreignField: "_id",
as: "description"
}
}
])
06/06/2019 MongoDB class by Alexandre Bergere 89
Index
06/06/2019 MongoDB class by Alexandre Bergere 90
Index
Indexes are special data structures [1] that store a small portion of the collection’s data set in an easy to
traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the
field. The ordering of the index entries supports efficient equality matches and range-based query
operations. In addition, MongoDB can return sorted results by using the ordering in the index.
06/06/2019 MongoDB class by Alexandre Bergere 91
Index
# Create
> db.collection.createIndex({'name':1})
# Get
> db.collection.getIndexes()
# Delete
> db.collection.dropIndex({'name':1})
06/06/2019 MongoDB class by Alexandre Bergere 92
$text
06/06/2019 MongoDB class by Alexandre Bergere 93
$text
$text performs a text search on the content of the fields indexed with a text index. A $text expression has the
following syntax:
{
$text:
{
$search: <string>,
$language: <string>,
$caseSensitive: <boolean>,
$diacriticSensitive: <boolean>
}
}
> db.articles.find( { $text: { $search:
"coffee" } } )
06/06/2019 MongoDB class by Alexandre Bergere 94
$text - indexation
Indexes
A collection can have at most
one text index.
> db.collection.createIndex( { comments: "text" } )
# You can index multiple fields for the text index:
> db.collection.createIndex(
{
subject: "text",
comments: "text"
}
)
First, create your index !
Wildcard Text Indexes
When creating a text index on multiple fields, you can also use the wildcard
specifier ($**). With a wildcard text index, MongoDB indexes every field
that contains string data for each document in the collection. The following
example creates a text index using the wildcard specifier:
db.collection.createIndex( { "$**": "text" } )
06/06/2019 MongoDB class by Alexandre Bergere 95
$text
Case Insensitivity
The version 3 text index supports the common C, simple S, and for Turkish
languages, the special T case foldings as specified in Unicode 8.0 Character
Database Case Folding.
The case foldings expands the case insensitivity of the text index to include
characters with diacritics, such as é and É, and characters from non-Latin
alphabets, such as “И” and “и” in the Cyrillic alphabet.
Version 3 of the text index is also diacritic insensitive. As such, the index
also does not distinguish between é, É, e, and E.
Previous versions of the text index are case insensitive for [A-z] only; i.e.
case insensitive for non-diacritics Latin characters only . For all other
characters, earlier versions of the text index treat them as distinct.
06/06/2019 MongoDB class by Alexandre Bergere 96
$text - indexation
Case Insensitivity
Match Any of the Search Terms
If the search string is a space-delimited string, $text operator performs a logical OR
search on each term and returns documents that contains any of the terms.
Search for a Phrase
To match the exact phrase as a single term, escape the quotes.
Exclude Documents That Contain a Term
A negated term is a term that is prefixed by a minus sign -. If you negate a term, the
$text operator will exclude the documents that contain those terms from the results.
Search a Different Language
Use the optional $language field in the $text expression to specify a language that
determines the list of stop words and the rules for the stemmer and tokenizer for the
search string.
If you specify a language value of "none", then the text search uses simple
tokenization with no list of stop words and no stemming.
> db.articles.find( { $text: { $search: "bake coffee cake" } } )
> db.articles.find( { $text: { $search: ""coffee shop"" } } )
> db.articles.find( { $text: { $search: "coffee -shop" } } )
> db.articles.find({ $text: { $search: "leche", $language: "es"
} })
06/06/2019 MongoDB class by Alexandre Bergere 97
TP – $text
1. Find in collection « companies » the following words: “Server” & “Software” in the fields
“description” and “name”.
06/06/2019 MongoDB class by Alexandre Bergere 98
TP – $text
# Request:
> db.companies.createIndex(
{
name: "text",
description: "text"
}
)
> db.companies.find( { $text: { $search: "Server Software" } } )
> db.companies.find( { $text: { $search: "Server Software" } },
{'description':1,'name':1} ).pretty()
06/06/2019 MongoDB class by Alexandre Bergere 99
Compass
06/06/2019 MongoDB class by Alexandre Bergere 100
MongoDB Compass
06/06/2019 MongoDB class by Alexandre Bergere 101
MongoDB Compass
06/06/2019 MongoDB class by Alexandre Bergere 102
MongoDB Compass
06/06/2019 MongoDB class by Alexandre Bergere 103
MongoDB Compass
Visualize, understand, and work with your geospatial data
Point and click to construct sophisticated queries, execute
them with the push of a button and Compass will display your
results both graphically and as sets of JSON documents.
A better approach to CRUD makes it easier to interact with your
data
Modify existing documents with greater confidence using the
intuitive visual editor, or insert new documents and clone or
delete existing ones in just a few clicks.
06/06/2019 MongoDB class by Alexandre Bergere 104
MongoDB Compass
Compass Community
Editions
View, add, and delete databases and collections X X
View and interact with documents with full CRUD functionality X X
Build and run ad hoc queries X X
View and optimize query performance with visual explain plans X X
Manage indexes: view stats, create, and delete X X
Create and execute aggregation pipelines X X
Kerberos, LDAP and x509 Authentication X
Schema Analysis X
Real Time Server Stats X
Document Validation X
06/06/2019 MongoDB class by Alexandre Bergere 105
MongoDB Compass
Compass Readonly Edition
New in version 1.12.0
A read-only version of MongoDB Compass is available which provides the ability to limit
certain CRUD operations within your organization. In this version, users are limited strictly
to read operations within MongoDB.
Compass Isolated Edition
New in version 1.14.0
Compass Isolated Edition restricts network requests to TLS-encrypted TCP connections to the
server chosen on the Connect screen. All other outbound connections are not permitted in this
edition.
06/06/2019 MongoDB class by Alexandre Bergere 106
TP - Compass
1. Insert the following artist: {“last_name”: “Van gogh”, "first_name": “Vincent”}
2. Add hobbies “pony” and “painting” to the artist 280.
3. Add "birth_date" to the schema validation.
4. Return artists from the 6th to the 9th ordered desc by their name.
5. Free test
06/06/2019 MongoDB class by Alexandre Bergere 107
Artist collection:
Hackolade
06/06/2019 MongoDB class by Alexandre Bergere 108
Hackolade
06/06/2019 MongoDB class by Alexandre Bergere 109
Replica set
06/06/2019 MongoDB class by Alexandre Bergere 110
Replica Set
A replica set in MongoDB is a group of mongod processes that maintain the same data set. Replica sets provide
redundancy and high availability, and are the basis for all production deployments. This section introduces
replication in MongoDB as well as the components and architecture of replica sets. The section also provides
tutorials for common tasks related to replica sets.
Replication provides redundancy and increases data availability. With multiple copies of data on different
database servers, replication provides a level of fault tolerance against the loss of a single database server.
In some cases, replication can provide increased read capacity as clients can send read operations to different
servers. Maintaining copies of data in different data centers can increase data locality and availability for
distributed applications. You can also maintain additional copies for dedicated purposes, such as disaster
recovery, reporting, or backup
06/06/2019 MongoDB class by Alexandre Bergere 111
Replica set
27017 27018
27019
Primary Arbiter
Secondary
REPLICATION
Types de serveur:
• primary
• secondary
• arbiter
• hidden
06/06/2019 MongoDB class by Alexandre Bergere 112
Replica set
06/06/2019 MongoDB class by Alexandre Bergere 113
Replica set
options
mongod --port 27001
--replSet name
--dbpath paht of data
--logpath user
--logappend (if the server shutdown)
--oplogSize 50
mongod --port 27017 --dbpath
"C:UsersalexaDocumentsMongoDBdata_primary" --replSet rs0 --
smallfiles --oplogSize 128
mongod --port 27018 --dbpath
"C:UsersalexaDocumentsMongoDBdata_secondary" --replSet rs0 --
smallfiles --oplogSize 128
mongod --port 27019 --dbpath
"C:UsersalexaDocumentsMongoDBdata_arbitrer" --replSet rs0 --
smallfiles --oplogSize 128
06/06/2019 MongoDB class by Alexandre Bergere 114
Replica set
Replica
Options:
• arbitrerOnly : true (à aucunes données et permet de voter lors d'un
nombre paire de serveur)
• priority : 0 (never primary) permet de donner un ordre sur le futur
primary en cas de problèmes
• hidden : true permet de cacher le serveur des clients, il ne peut être
primary
• slaveDelay : Mets à jour les data avec un delay (ex : 8*3600 récupère les
données avec toujours 8h de retard) (rajouter hidden:true)
• vote : 2 (ex) permet de rajouter des votes (déconseiller, autant utiliser
arbiterOnly) [ex : Srv 1 (vote 2) Srv 2 (vote 1) si Srv tombe, Srv2 a 1/3, il
devient pas primary]
06/06/2019 MongoDB class by Alexandre Bergere 115
Replica set
Initialisation
# Use rs.initiate() on one and only one
member of the replica set:
> rs.initiate({
_id: "rs0",
version: 1,
members: [
{ _id: 0, host : "localhost:27017"
}
, { _id: 1, host :
"localhost:27018" }
]
}
)
# Add other replica:
> rs.add("localhost:27018")
> rs.addArb(" localhost :27019")
# Delete a server from the replicaSet:
> rs.remove("localhost:27018")
# Check the
configuration:
> rs.conf()
06/06/2019 MongoDB class by Alexandre Bergere 116
Replica set
Command
# In each Replica:
> rs.slaveOk()
# Check status:
> rs.status()
The secondary only accepts writes that it gets through replication.
To allow queries on a secondary, we must tell Mongo that we are okay with
reading from the secondary.
06/06/2019 MongoDB class by Alexandre Bergere 117
Replica set
Reconfiguration
# For the hidden:
> cfg = rs.conf()
> cfg.members[2].priority = 0
> cfg.members[2]. slaveDelay = 86400
> cfg.members[2].hidden = true
> rs.reconfig(cfg)
# For the hidden:
> rs.remove("localhost:27018")
> rs.addArb("localhost :27018")
To do only on the PRIMARY !
06/06/2019 MongoDB class by Alexandre Bergere 118
Fire & Forget strategy
You can configure MongoDB to fire-and-forget, sending off a write to the server without
waiting for an acknowledgment.
For high-volume, low-value data (like clickstreams and logs), fire-and-forget-style writes can be
ideal.
You can also configure MongoDB to guarantee that a write has gone to multiple replicas before
considering it committed. For important data, a safe mode setting is necessary.
06/06/2019 MongoDB class by Alexandre Bergere 119
TP – Replica set
1. Init 3 replicas.
2. Import the dump on the primary.
3. Put one of the replicas in backup, adjust its reception delay to 24h.
4. Try to insert data into a secondary.
5. Insert data into the primary and check its persistence on the network.
6. Add a fourth replica and configure it as an arbiter (check data behaviour on this one).
7. Import the file “place.json”. Is it persistent on all the network?
8. Set the priority to 2 for the primary, shutdown it and start it back.
06/06/2019 MongoDB class by Alexandre Bergere 120
TP – Replica set
06/06/2019 MongoDB class by Alexandre Bergere 121
# 1. Init 3 replica:
mongod --port 27017 --dbpath C:UsersalexaDocumentsCoursMongoDB2018-2019data1 --replSet rs0 --
smallfiles --oplogSize 128
mongod --port 27018 --dbpath C:UsersalexaDocumentsCoursMongoDB2018-2019data2 --replSet rs0 --
smallfiles --oplogSize 128
mongod --port 27019 --dbpath C:UsersalexaDocumentsCoursMongoDB2018-2019data3 --replSet rs0 --
smallfiles --oplogSize 128
mongo --port 27017
> rs.initiate()
> rs.conf()
> rs.add("localhost:27018")
> rs.add("localhost:27019")
mongo --port 27018
> rs.slaveOk()
mongo --port 27018
> rs.slaveOk()
TP – Replica set
06/06/2019 MongoDB class by Alexandre Bergere 122
# 2. Import the dump on the primary:
mongodump --archive --db crunchbase --port 27058 | mongorestore --archive --port 27017
# 3. Put one of the replicas in backup, adjust its reception delay to 24h:
> cfg = rs.conf()
> cfg.members[2].priority = 0
> cfg.members[2].hidden = true
> rs.reconfig(cfg)
# 6. Add a fourth replica and configure it as an arbiter (check data behaviour on this one):
mongod --port 27020 --dbpath C:UsersalexaDocumentsCoursMongoDB2018-2019data4 --replSet rs0 --
smallfiles --oplogSize 128
mongo --port 27017
> rs.addArb("localhost:27020")
mongo --port 27020
> rs.slaveOk()
TP – Replica set
06/06/2019 MongoDB class by Alexandre Bergere 123
# 7. Set the priority to 2 for the primary, shutdown it and start it back:
> cfg = rs.conf()
> cfg.members[3].priority = 2
> rs.reconfig(cfg)
Aggregation
06/06/2019 MongoDB class by Alexandre Bergere 124
Aggregation
Swiss Army knife
Executes in native code
o Written in C++
o JSON parameter
Flexible, funcional, simple
o Operation pipeline
o Computational expressions
06/06/2019 MongoDB class by Alexandre Bergere 125
Aggregation
Operator Description
$match Filter documents
$project Reshape documents
$group Summarize documents
$unwind Expand arrays in documents
$sort Order documents
$limit / $skip Paginate documents
$redact Restrict documents
$geoNear Proximity sort documents
$let, $map Define variables
06/06/2019 MongoDB class by Alexandre Bergere 126
$match
# Matching field values
> {$match:{
language:"Russian"
}
{
title:"War and Peace",
pages:1440,
language:"Russian"
}
# Matching with query operators
> {$match:{
pages:{$gt:100}
}
{
title:"War and Peace",
pages:1440,
language:"Russian"
},
{
title:"Atlas Shrugged",
pages:1088,
language:"English"
}
06/06/2019 MongoDB class by Alexandre Bergere 127
$project
# Renaming and computing fields
> {$project:{
avgChapterLength:{
$divide:["$pages", "$chapters" ]
},
lang: "$language"
}}
{
_id:375,
avgChapterLength: 24,2222
lang:"English"
}
# Including & excluding fields
> {$project:{
_id:0,
title:1,
language:1
}}
{
title:"Great Gatsby" ,
language:"English"
}
06/06/2019 MongoDB class by Alexandre Bergere 128
$group
# Collect distinct values
> {$group:{
_id:"$langugage",
titles:{$addToSet:"$title"}
}}
{
_id:"English",
titles:["Atlas Shrugged" , "The
Great Gatsby"]
},
{
_id:"Russian",
titles:["War and Peace"]
}
# Calculating average, summing fields…
> {$group:{
_id:"$langugage",
pages:{$sum:"$pages"},
books:{$sum:1},
avgPages:{$avg:"$pages"}
}}
{
_id:"Russian",
pages:1440,
books:1,
avgPages:1440
}
06/06/2019 MongoDB class by Alexandre Bergere 129
$unwind
# Collect distinct values
> {$unwind:{
"subjects"
}
{
title:"The Great Gatsby",
ISBN:"9762832930920323" ,
subjects:"Long Island"
},
{
title:"The Great Gatsby",
ISBN:"9762832930920323" ,
subjects:"New York"
},
{
title:"The Great Gatsby",
ISBN:"9762832930920323" ,
subjects:"1920s"
}
{
title:"The Great Gatsby",
ISBN:"9762832930920323" ,
subjects:[
"Long Island",
"New York",
"1920s"
]
}
06/06/2019 MongoDB class by Alexandre Bergere 130
TP - Aggregation
1. How many companies has more than 999 employees and was founded in or after 2000?
2. Number of companies and Number of employees group by founded year, ordrer by founded_year
desc?
3. How many companies group by category_code, with a list of all included companies names, with
category_code filter on medical or government?
4. How many companies has more than 1000 employees and was founded after 2000 (with agg.
function)?
06/06/2019 MongoDB class by Alexandre Bergere 131
TP - Aggregation
06/06/2019 MongoDB class by Alexandre Bergere 132
# 1. How many companies has more than 1000 employees and was founded after 2000?
> db.companies.count({$and:[{"number_of_employees":{$gte:1000}},{"founded_year":{$gte:2000}}]},{})
# 2. Number of companies and Number of employees group by founded year, order by founded_year desc?
> db.companies.aggregate ([
{ $sort : { founded_year: 1} },
{ "$group" : {
"_id" : "$founded_year",
"NumberOfCompanies" : {$sum : 1},
"NumberOfEmployees":{$sum : "$number_of_employees"}
}
}
]).pretty()
TP - Aggregation
06/06/2019 MongoDB class by Alexandre Bergere 133
# 3. How many companies group by category_code, with a list of all included companies names, with
category_code filter on medical or government?
> db.companies.aggregate ([
{ "$match":{
category_code: {$in:["medical","government"]}
}
},
{ "$group" : {
"_id" : "$category_code",
"NumberOfCompanies" : {"$sum" : 1},
"Companies":{$addToSet:"$name"}
}
}
]).pretty()
TP - Aggregation
06/06/2019 MongoDB class by Alexandre Bergere 134
# 4. How many companies has more than 1000 employees and was founded after 2000 (with agg. function)?
> db.companies.aggregate ([
{ "$match":{
$and:[{"number_of_employees":{$gte:1000}},{"founded_year":{$gte:2000}}]
}
},
{ "$group" : {
"_id" : null,
"NumberOfCompanies" : {"$sum" : 1}
}
}
]).pretty()
> db.companies.aggregate ([
{ "$match":{
$and:[{"number_of_employees":{$gte:1000}},{"founded_year":{$gte:2000}}]
}
},
{ "$count" : "NumberOfCompanies" }
]).pretty()
Authentification
06/06/2019 MongoDB class by Alexandre Bergere 135
Authentication vs Authorization
Authentification Authorization
Verify the identity of
a user.
Verify the privileges of a
user.
06/06/2019 MongoDB class by Alexandre Bergere 136
Authentification
Client/User Auth
SCRAM-SHA-1
MONGODB-CR
X.509
LDAP
Kerberos
Internal Auth
Keyfile (SCRAM-SHA-1)
X.509
Community Enterprise
06/06/2019 MongoDB class by Alexandre Bergere 137
Authentification
BUSINESS NEEDS MONGODB SECURITY FEATURES
Authentication SCRAM, LDAP, Kerberos, x.509 Certificates
Authorization Built-in Roles, User-Defined Roles, Field-Level Redaction
Auditing Admin, DML, DDL, Role-Based
Encryption Network: SSL (with FIPS 140-2)
Disk : Encrypted Storage Engine or Partner Solutions
06/06/2019 MongoDB class by Alexandre Bergere 138
Localhost Exception
The localhost exception allows you to enable access control and then create the first user in the
system. With the localhost exception, after you enable access control, connect to the localhost
interface and create the first user in the admin database. The first user must have privileges to
create other users, such as a user with the userAdmin or userAdminAnyDatabase role.
Changed in version 3.0: The localhost exception changed so that these connections only have
access to create the first user on the admin database. In previous versions, connections that
gained access using the localhost exception had unrestricted access to the MongoDB instance.
The localhost exception applies only when there are no users created in the MongoDB instance
and only when you’re connected to database via the localhost interface, meaning in the same
server.
06/06/2019 MongoDB class by Alexandre Bergere 139
Client/User
Authentication
Mechanism
Mechanism Description
SCRAM-SHA-1
• Default mechanism
• Challenge / Response
• Username / Password
• IETF Standard
MONGODB-CR
• Challenge / Response
• Replaced by SCRAM-SHA-1
• Username / Password
• Deprecated as of MongoDB 3.0
X.509
• Certificate based
• Introduced in MongoDB 2.6
• TLS
LDAP
• Lightweight Director Access Protocol
• Used for directory information
• External authentication mechanism
Kerberos
• Developed at MIT
• Design for secure authentication
• External authentication mechanism
06/06/2019 MongoDB class by Alexandre Bergere 140
Client/User
Authentication
Initialisation
mongod --auth --dbpath C:UsersalexaDocumentsMongoDBdata
# Request:
> use admin
db.createUser(
{
user: "UserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
The first thing you are allowed to do when connected to an
authenticated Mongo server is you’re allowed to create the firste user
in the database.
With that first user you create then create other users.
06/06/2019 MongoDB class by Alexandre Bergere 141
Client/User
Authentication
Authentification methods
After you’re created the first user in the database, the localhost exception will
not apply.
Always specify the database in which the user is created.
mongo admin --port 27017 -u "UserAdmin" -p "abc123"
OR:
mongo –port 27017 -u "UserAdmin" -p "abc123" –
authenticationDatabase=admin
> use admin
> db.auth(‘UserAdmin’, ‘abc123’ )
OR
When adding a user, you create the user in a specific database. This database is
the authentication database for the user.
A user can have privileges across different databases; i.e. a user’s privileges are
not limited to the authentication database. By assigning to the user roles in other
databases, a user created in one database can have permissions to act on other
databases.
06/06/2019 MongoDB class by Alexandre Bergere 142
Client/User
Authentication
Informations
# Returns users information:
> db.getUsers()
> db.system.users.find()
# Returns users information for a specified user:
> db.getUsers(username)
06/06/2019 MongoDB class by Alexandre Bergere 143
Client/User
Authentication
Role
Roles are grouped of privileges, actions over resources, that are granted to
users over a given namespace (database).
{
role: "<name>",
privileges: [
{ resource: { <resource> }, actions: [ "<action>", ... ] },
...
],
roles: [
{ role: "<role>", db: "<database>" } | "<role>",
...
]
}
06/06/2019 MongoDB class by Alexandre Bergere 144
Client/User
Authentication
Role
06/06/2019 MongoDB class by Alexandre Bergere 145
Client/User
Authentication
Role
All roles :
https://docs.mongodb.com/manual/reference/bui
lt-in-roles/
read : the role provides read access by granting the following actions
collStats
dbHash
dbStats
find
killCursors
listIndexes
listCollections
06/06/2019 MongoDB class by Alexandre Bergere 146
Client/User
Authentication
Action
Query & Write
find
Insert
remove
update
bypassDocumentValidationAll action:
https://docs.mongodb.com/manual/reference/
privilege-actions/06/06/2019 MongoDB class by Alexandre Bergere 147
Client/User
Authentication
Ressources
resource: {
db: "users"
, collection: "usersCollection"
,cluster: true
,anyResource: true
}
06/06/2019 MongoDB class by Alexandre Bergere 148
Client/User
Authentication
Role
> use admin
db.createRole(
{
role: "myClusterwideAdmin",
privileges: [
{ resource: { cluster: true }, actions: [ "addShard" ] },
{ resource: { db: "config", collection: "" }, actions: [
"find", "update", "insert", "remove" ] },
{ resource: { db: "users", collection: "usersCollection" },
actions: [ "update", "insert", "remove" ] },
{ resource: { db: "", collection: "" }, actions: [ "find" ] }
],
roles: [
{ role: "read", db: "admin" }
]
},
{ w: "majority" , wtimeout: 5000 }
)
06/06/2019 MongoDB class by Alexandre Bergere 149
Client/User
Authentication
Monitoring role
> use admin
db.createRole(
{
role: "manageOpRole",
privileges: [
{ resource: { cluster: true }, actions: [ "killop", "inprog" ]
},
{ resource: { db: "", collection: "" }, actions: [
"killCursors" ] }
],
roles: []
}
)
db.createRole(
{
role: "mongostatRole",
privileges: [
{ resource: { cluster: true }, actions: [ "serverStatus" ] }
],
roles: []
}
)
06/06/2019 MongoDB class by Alexandre Bergere 150
Client/User
Authentication
Role information
# Returns roles information:
> db.getRoles("read", {showPrivileges:true})
# Helpful:
> var readRoles = db.getRoles("read", {showPrivileges:true})
> readRoles.privileges[0]
06/06/2019 MongoDB class by Alexandre Bergere 151
Client/User
Authentication
Role modification
# Add a role:
> db.grantRolesToUser(
"reportsUser",
[
{ role: "read", db: "accounts" }
]
)
# Revoke a role:
> db.revokeRolesFromUser(
“myTester",
[
{ role: "readWrite", db: “crunchbase" }
]
)
06/06/2019 MongoDB class by Alexandre Bergere 152
Client/User
Authentication
User
# Create a new user and attribute role:
> db.createUser(
{
user: "myTester",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "crunchbase" },
{ role: "read", db: "test" } ]
}
)
06/06/2019 MongoDB class by Alexandre Bergere 153
TP – Client/User Authentication
1. Create an admin user with the role “userAdminAnyDatabase” on the database “admin”.
2. Create a user “myTester” with a reader/writer role on the database “crunchbase”.
3. Create a user “Reader” with a reader role on the database “crunchbase.
4. Export the collection “artists”, delete it and import it back.
06/06/2019 MongoDB class by Alexandre Bergere 154
TP – Client/User Authentication
06/06/2019 MongoDB class by Alexandre Bergere 155
# 1. Create an admin user with the role “userAdminAnyDatabase” on the database “admin”.
mongod --auth --port 27017 --dbpath C:UsersalexaDocumentsCoursMongoDB2017-2018datadata
mongo
> use admin
> db.createUser(
{
user: "UserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
TP – Client/User Authentication
06/06/2019 MongoDB class by Alexandre Bergere 156
# 2. Create a user “myTester” with a reader/writer role on the database “crunchbase”.
mongo --port 27017 -u "UserAdmin" -p "abc123" --authenticationDatabase "admin"
OR
mongo
> use admin
> db.auth("UserAdmin", "abc123" )
> db.createUser(
{
user: "myTester",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "crunchbase" } ]
}
)
TP – Client/User Authentication
06/06/2019 MongoDB class by Alexandre Bergere 157
# 3. Create a user “Reader” with a reader role on the database “crunchbase.
> db.createUser(
{
user: "myReader",
pwd: "xyz123",
roles: [ { role: "read", db: "crunchbase" } ]
}
)
# 4. Create a user “Reader” with a reader role on the database “crunchbase.
mongoexport -d crunchbase -c companies –out C:UsersalexaDocumentsMongoDBsrccompanies_export.json
mongoimport -d crunchbase -c companies -u "myTester" -p "xyz123" --authenticationDatabase "crunchbase"
C:UsersalexaDocumentsMongoDBsrccompanies.json
Internal
Authentication
Mechanism
Mechanism Description
Keyfile
(SCRAM-SHA-1)
• shared password
• copy exists on each member
• 6-1024 Base64 characters
• whitespace ignored
x.509
• certificate based
• recommended to issue different certs per member
Members of a replica set or sharded cluster must prove who they are.
06/06/2019 MongoDB class by Alexandre Bergere 158
Internal
Authentication
Shared / ReplicaSet authentication
With Keyfile access
1. Create a keyfile
Create a keyfile.
With keyfile authentication, each mongod instances in the replica set uses the
contents of the keyfile as the shared password for authenticating other members
in the deployment. Only mongod instances with the correct keyfile can join the
replica set.
2. Copy the keyfile to each replica set member
Copy the keyfile to each server hosting the replica set members. Ensure that the
user running the mongod instances is the owner of the file and can access the
keyfile.
3. Enable authentication for each member of the replica set.
openssl rand -base64 756 > <path-to-keyfile>
mongod --dbpath <path> --port <port> --replSet <replicaSetName> --fork
--keyFile <path-to-keyfile>
Update Existing Deployment
06/06/2019 MongoDB class by Alexandre Bergere 159
Internal
Authentication
Shared / ReplicaSet authentication
With Keyfile access
4. Add first user
Add a user with the userAdminAnyDatabase role.
5. Authenticate as the user administrator
6. Create additional users as needed for your deployment
> use admin
> db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
> mongo --port 27017 -u "myUserAdmin" -p "abc123" --
authenticationDatabase "admin"
Update Existing Deployment
> db.createUser({
"user":"AdminCluster"
,"pwd":"password"
,roles:[{"role":"clusterAdmin","db":"admin"}]
})
06/06/2019 MongoDB class by Alexandre Bergere 160
Internal
Authentication
Shared / ReplicaSet authentication
With Keyfile access
Follow replicaset & Update Existing Deployment.
OR
Or follow the link bellow: https://docs.mongodb.com/v3.0/tutorial/enable-internal-
authentication/ (Deploy New Replica Set with Access Control)
Deploy New Replica Set
with Access Control
06/06/2019 MongoDB class by Alexandre Bergere 161
Mongo DB Atlas
06/06/2019 MongoDB class by Alexandre Bergere 162
Mongo DB Atlas
DAAS : Database As A Service • Schema design
• Query and index optimization
• Server size selection - you must select the appropriate size of server,
coupled with IO and storage capacity
• Capacity planning - you must determine when you need additional
capacity, typically using the monitoring telemetry provided by
MongoDB Atlas, but you can make these changes with no downtime
• Initiating database restores
• How much you use
06/06/2019 MongoDB class by Alexandre Bergere 163
Mongo DB Cloud Manager
06/06/2019 MongoDB class by Alexandre Bergere 164
MongoDB Atlas vs MongoDB Cloud Manager
Feature Atlas Cloud Manager
Monitoring
Alert
API
Backup
Settings
Maintenance
Infrastructure
06/06/2019 MongoDB class by Alexandre Bergere 165
TP - MongoDB Atlas
06/06/2019 MongoDB class by Alexandre Bergere 166
Connector for bi
06/06/2019 MongoDB class by Alexandre Bergere 167
Connector for bi
06/06/2019 MongoDB class by Alexandre Bergere 168
TP – Connector for bi
Follow the link : https://docs.mongodb.com/bi-connector/master
06/06/2019 MongoDB class by Alexandre Bergere 169
MongoDB
06/06/2019 MongoDB class by Alexandre Bergere 170
MongoDB & Hadoop
06/06/2019 MongoDB class by Alexandre Bergere 171
MongoDB & Spark
06/06/2019 MongoDB class by Alexandre Bergere 172
Mtools
06/06/2019 MongoDB class by Alexandre Bergere 173
Mtools
The following tools are in the mtools collection:
mlogfilter : Slices log files by time, merges log files, filters slow queries, finds table scans, shortens log lines, filters by
other attributes, convert to JSON
mloginfo : returns info about log file, like start and end time, version, binary, special sections like restarts,
connections, distinct view
mplotqueries : visualize log files with different types of plots (requires matplotlib)
mlogvis : creates a self-contained HTML file that shows an interactive visualization in a web browser (as an
alternative to mplotqueries)
mlaunch : a script to quickly spin up local test environments, including replica sets and sharded systems (requires
pymongo)
06/06/2019 MongoDB class by Alexandre Bergere 174
MongoDB Charts
MongoDB Charts is the fastest and
easiest way to build visualizations of
MongoDB data.
(beta)
06/06/2019 MongoDB class by Alexandre Bergere 175
Change Streams
More info.
Change streams allow applications to access real-time data changes without the complexity and risk of tailing the oplog.
Applications can use change streams to subscribe to all data changes on a collection and immediately react to them.
06/06/2019 MongoDB class by Alexandre Bergere 176
Stitch
Full access to MongoDB, declarative read/write
controls, and integration with your choice of services
MongoDB Stitch lets developers focus on building applications rather than on managing data manipulation code, service integration, or
backend infrastructure. Whether you’re just starting up and want a fully managed backend as a service, or you’re part of an enterprise and
want to expose existing MongoDB data to new applications, Stitch lets you focus on building the app users want, not on writing boilerplate
backend logic.
06/06/2019 MongoDB class by Alexandre Bergere 177
THE END
06/06/2019 MongoDB class by Alexandre Bergere 178
Support
MongoDB in action, 2nd Edition docs.mongodb.com
06/06/2019 MongoDB class by Alexandre Bergere 179
Summer Internship
https://www.mongodb.com/careers/college-students
06/06/2019 MongoDB class by Alexandre Bergere 180
Learning
https://www.university.mongodb.com
06/06/2019 MongoDB class by Alexandre Bergere 181

Weitere ähnliche Inhalte

Was ist angesagt?

H2O Machine Learning with KNIME Analytics Platform - Christian Dietz - H2O AI...
H2O Machine Learning with KNIME Analytics Platform - Christian Dietz - H2O AI...H2O Machine Learning with KNIME Analytics Platform - Christian Dietz - H2O AI...
H2O Machine Learning with KNIME Analytics Platform - Christian Dietz - H2O AI...
Sri Ambati
 

Was ist angesagt? (20)

R, Spark, Tensorflow, H20.ai Applied to Streaming Analytics
R, Spark, Tensorflow, H20.ai Applied to Streaming AnalyticsR, Spark, Tensorflow, H20.ai Applied to Streaming Analytics
R, Spark, Tensorflow, H20.ai Applied to Streaming Analytics
 
Architecting Analytic Pipelines on GCP - Chicago Cloud Conference 2020
Architecting Analytic Pipelines on GCP - Chicago Cloud Conference 2020Architecting Analytic Pipelines on GCP - Chicago Cloud Conference 2020
Architecting Analytic Pipelines on GCP - Chicago Cloud Conference 2020
 
How Customers Are Using the IBM Data Science Experience - Expected Cases and ...
How Customers Are Using the IBM Data Science Experience - Expected Cases and ...How Customers Are Using the IBM Data Science Experience - Expected Cases and ...
How Customers Are Using the IBM Data Science Experience - Expected Cases and ...
 
From RDBMS to MongoDB
From RDBMS to MongoDBFrom RDBMS to MongoDB
From RDBMS to MongoDB
 
MongoDB and Azure Databricks
MongoDB and Azure DatabricksMongoDB and Azure Databricks
MongoDB and Azure Databricks
 
Databricks delta
Databricks deltaDatabricks delta
Databricks delta
 
MongoDB World 2019: Ticketek: Scaling to Global Ticket Sales with MongoDB Atlas
MongoDB World 2019: Ticketek: Scaling to Global Ticket Sales with MongoDB AtlasMongoDB World 2019: Ticketek: Scaling to Global Ticket Sales with MongoDB Atlas
MongoDB World 2019: Ticketek: Scaling to Global Ticket Sales with MongoDB Atlas
 
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...
 
How data modelling helps serve billions of queries in millisecond latency wit...
How data modelling helps serve billions of queries in millisecond latency wit...How data modelling helps serve billions of queries in millisecond latency wit...
How data modelling helps serve billions of queries in millisecond latency wit...
 
The Scout24 Data Landscape Manifesto: Building an Opinionated Data Platform
The Scout24 Data Landscape Manifesto: Building an Opinionated Data PlatformThe Scout24 Data Landscape Manifesto: Building an Opinionated Data Platform
The Scout24 Data Landscape Manifesto: Building an Opinionated Data Platform
 
H2O Machine Learning with KNIME Analytics Platform - Christian Dietz - H2O AI...
H2O Machine Learning with KNIME Analytics Platform - Christian Dietz - H2O AI...H2O Machine Learning with KNIME Analytics Platform - Christian Dietz - H2O AI...
H2O Machine Learning with KNIME Analytics Platform - Christian Dietz - H2O AI...
 
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
 
Rise of the Data Cloud
Rise of the Data CloudRise of the Data Cloud
Rise of the Data Cloud
 
The Scout24 Data Platform (A Technical Deep Dive)
The Scout24 Data Platform (A Technical Deep Dive)The Scout24 Data Platform (A Technical Deep Dive)
The Scout24 Data Platform (A Technical Deep Dive)
 
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 San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
 
MongoDB and the Internet of Things
MongoDB and the Internet of ThingsMongoDB and the Internet of Things
MongoDB and the Internet of Things
 
MongoDB .local Chicago 2019: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local Chicago 2019: MongoDB Atlas Data Lake Technical Deep DiveMongoDB .local Chicago 2019: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local Chicago 2019: MongoDB Atlas Data Lake Technical Deep Dive
 
The Scout24 Data Platform - a technical deep dive
The Scout24 Data Platform - a technical deep diveThe Scout24 Data Platform - a technical deep dive
The Scout24 Data Platform - a technical deep dive
 
Scaling Data Quality @ Netflix
Scaling Data Quality @ NetflixScaling Data Quality @ Netflix
Scaling Data Quality @ Netflix
 

Ähnlich wie MongoDB classes 2019

ArangoDB – A different approach to NoSQL
ArangoDB – A different approach to NoSQLArangoDB – A different approach to NoSQL
ArangoDB – A different approach to NoSQL
ArangoDB Database
 
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
BedCon 2013 - Java Persistenz-Frameworks für MongoDBBedCon 2013 - Java Persistenz-Frameworks für MongoDB
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
Tobias Trelle
 
Everything You Need to Know About MongoDB Development.pptx
Everything You Need to Know About MongoDB Development.pptxEverything You Need to Know About MongoDB Development.pptx
Everything You Need to Know About MongoDB Development.pptx
75waytechnologies
 

Ähnlich wie MongoDB classes 2019 (20)

Introduction to mongodb
Introduction to mongodbIntroduction to mongodb
Introduction to mongodb
 
An introduction to MongoDB by César Trigo #OpenExpoDay 2014
An introduction to MongoDB by César Trigo #OpenExpoDay 2014An introduction to MongoDB by César Trigo #OpenExpoDay 2014
An introduction to MongoDB by César Trigo #OpenExpoDay 2014
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
 
how_can_businesses_address_storage_issues_using_mongodb.pdf
how_can_businesses_address_storage_issues_using_mongodb.pdfhow_can_businesses_address_storage_issues_using_mongodb.pdf
how_can_businesses_address_storage_issues_using_mongodb.pdf
 
how_can_businesses_address_storage_issues_using_mongodb.pptx
how_can_businesses_address_storage_issues_using_mongodb.pptxhow_can_businesses_address_storage_issues_using_mongodb.pptx
how_can_businesses_address_storage_issues_using_mongodb.pptx
 
MongoDB - An Agile NoSQL Database
MongoDB - An Agile NoSQL DatabaseMongoDB - An Agile NoSQL Database
MongoDB - An Agile NoSQL Database
 
Mongo db operations_v2
Mongo db operations_v2Mongo db operations_v2
Mongo db operations_v2
 
ArangoDB – A different approach to NoSQL
ArangoDB – A different approach to NoSQLArangoDB – A different approach to NoSQL
ArangoDB – A different approach to NoSQL
 
ArangoML Pipeline Cloud - Managed Machine Learning Metadata
ArangoML Pipeline Cloud - Managed Machine Learning MetadataArangoML Pipeline Cloud - Managed Machine Learning Metadata
ArangoML Pipeline Cloud - Managed Machine Learning Metadata
 
MongoDB presentation
MongoDB presentationMongoDB presentation
MongoDB presentation
 
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
BedCon 2013 - Java Persistenz-Frameworks für MongoDBBedCon 2013 - Java Persistenz-Frameworks für MongoDB
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
 
MongoDB and Spring - Two leaves of a same tree
MongoDB and Spring - Two leaves of a same treeMongoDB and Spring - Two leaves of a same tree
MongoDB and Spring - Two leaves of a same tree
 
MongoDB + Spring
MongoDB + SpringMongoDB + Spring
MongoDB + Spring
 
Group1_mongoDB_presentation.pdf
Group1_mongoDB_presentation.pdfGroup1_mongoDB_presentation.pdf
Group1_mongoDB_presentation.pdf
 
Discover BigQuery ML, build your own CREATE MODEL statement
Discover BigQuery ML, build your own CREATE MODEL statementDiscover BigQuery ML, build your own CREATE MODEL statement
Discover BigQuery ML, build your own CREATE MODEL statement
 
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
 
Full-stack Web Development with MongoDB, Node.js and AWS
Full-stack Web Development with MongoDB, Node.js and AWSFull-stack Web Development with MongoDB, Node.js and AWS
Full-stack Web Development with MongoDB, Node.js and AWS
 
MongoDB DOC v1.5
MongoDB DOC v1.5MongoDB DOC v1.5
MongoDB DOC v1.5
 
Everything You Need to Know About MongoDB Development.pptx
Everything You Need to Know About MongoDB Development.pptxEverything You Need to Know About MongoDB Development.pptx
Everything You Need to Know About MongoDB Development.pptx
 
Mdb dn 2016_07_elastic_search
Mdb dn 2016_07_elastic_searchMdb dn 2016_07_elastic_search
Mdb dn 2016_07_elastic_search
 

Kürzlich hochgeladen

Kürzlich hochgeladen (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 🐘
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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)
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

MongoDB classes 2019

  • 1. Mongo DB 06/06/2019 MongoDB class by Alexandre Bergere 1
  • 2. { Part One:[ Big Data No SQL ], Part Two:[ Mongo DB Architecture & Modelization CRUD Replication Security Aggregation Mongo DB Atlas ] } 06/06/2019 MongoDB class by Alexandre Bergere 2
  • 3. MongoDB class by Alexandre Bergere 3 alexandre.bergere@gmail.com https://fr.linkedin.com/in/alexandrebergere @AlexPhile Avanade 2016 - 2019 Sr Anls, Data Engineering Worked for 3 years as a senior analyst at Avanade France, I have developed my skills in data analysis (MSBI, Power BI, R, Python, Spark, Cosmos DB) by working on innovative projects and proofs of concept in the energy industry. ESAIP Teacher 2016 - x Data Freelance 2019 - x
  • 4. 06/06/2019 MongoDB class by Alexandre Bergere 4 Sources A lot of the sources for making this courses provided from docs.mongodb.com or https://www.university.mongodb.com.
  • 5. BIG DATA 06/06/2019 MongoDB class by Alexandre Bergere 5
  • 6. Data Source Big Data Architecture Data Ingestion & Processing Data Analytics Data Visualization Data Storage Data Lake / Data Warehouse ETL Messaging Queue Data Management Batch / Streaming Machine Learning MOLAP Data Quality No SQL HDFS SQL Web Apps Visualizations tools Visuals Query RDBMS Social Media Device IoT / Sensors Files (log, Unst) 06/06/2019 MongoDB class by Alexandre Bergere 6 Object store
  • 7. Data Storage Relational data store HDFS Key Value data store Columnar data store Object store Search data store Graph data store Document data store 06/06/2019 MongoDB class by Alexandre Bergere 7
  • 8. NO SQL 06/06/2019 MongoDB class by Alexandre Bergere 8
  • 9. Data management NoSQL OLAP System R & SQL Cobol Hierarchic model 06/06/2019 MongoDB class by Alexandre Bergere 9 70’s 80’s 90’s 20th
  • 10. NoSQL OLAP System R & SQL Cobol Hierarchic model Codd's 12 Rules o Rule 1: Information Rule o Rule 2: Guaranteed Access Rule o Rule 3: Systematic Treatment of NULL Values o Rule 4: Active Online Catalog o Rule 5: Comprehensive Data Sub-Language Rule o Rule 6: View Updating Rule o Rule 7: High-Level Insert, Update, and Delete Rule o Rule 8: Physical Data Independence o Rule 9: Logical Data Independence o Rule 10: Integrity Independence o Rule 11: Distribution Independence o Rule 12: Non-Subversion Rule Data management RDBMS 06/06/2019 MongoDB class by Alexandre Bergere 10
  • 11. NoSQL OLAP System R & SQL Cobol Hierarchic model Data management OLAP : Online Analytical Processing 06/06/2019 MongoDB class by Alexandre Bergere 11
  • 12. Data management No SQL NoSQL OLAP System R & SQL Cobol Hierarchic model Benefits: o performance o volume o variety 06/06/2019 MongoDB class by Alexandre Bergere 12 Different type of data storage: o Key-value o Document data store o Columnar data store o Graph data store o Search data store
  • 13. MongoDB 06/06/2019 MongoDB class by Alexandre Bergere 13
  • 14. Created in 2007 & first release in 2010. Easy and simple … as a leaf. Document data store & Schemaless. 06/06/2019 MongoDB class by Alexandre Bergere 14
  • 15. Nexus Architecture 06/06/2019 MongoDB class by Alexandre Bergere 15
  • 16. Drivers & Frameworks 06/06/2019 MongoDB class by Alexandre Bergere 16
  • 17. Mongo DB is easy For many developers, data model goes hand in hand with object mapping, and for that purpose you may have used an object-relational mapping library, such as Java’s Hibernate framework or Ruby’s ActiveRecord. Such libraries can be useful for efficiently building applications with a RDBMS, but they’re less necessary with MongoDB. This is due in part to the fact that a document is already an object- like representation. It’s also partly due to the MongoDB drivers, which already provide a fairly high-level interface to MongoDB. Without question, you can build applications on MongoDB using the driver interface alone. 06/06/2019 MongoDB class by Alexandre Bergere 17
  • 18. Use cases o Web application (mongoDB is well-suited as primary datastore for web application) o Agile development o Analytics and logging o Caching o Variable Schemas 06/06/2019 MongoDB class by Alexandre Bergere 18
  • 19. The case for adding NoSQL o Large volumes of rapidly changing structured, semi-structured, and unstructured data o Agile sprints, quick schema iteration, and frequent code pushes o API-driven, object-oriented programming that is easy to use and flexible o Geographically distributed scale-out architecture instead of expensive, monolithic architecture Consider, for example, enterprise resource planning (ERP), a standard for relational databases. What if you want to offer ERP forms users can actually modify if they need to? A document- based NoSQL database such as MongoDB can provide that functionality without requiring you to rebuild your whole data schema every time a user wants to change the data format. 06/06/2019 MongoDB class by Alexandre Bergere 19
  • 20. Mongo DB history 06/06/2019 MongoDB class by Alexandre Bergere 20
  • 21. Mongo DB 4.0 : ACID transactions More info. 06/06/2019 MongoDB class by Alexandre Bergere 21
  • 22. Leader in The Forrester Wave™: Big Data NoSQL, Q1 2019 o “MongoDB remains the most popular NoSQL database” o Used by more than 8,000 companies, including many Fortune 100 companies. o Highest possible scores in 21 of the 26 criteria. 06/06/2019 MongoDB class by Alexandre Bergere 22
  • 23. Companies 06/06/2019 MongoDB class by Alexandre Bergere 23
  • 24. White papers MongoDB – BI & Analytics MongoDB – Kafka MongoDB – Spark 06/06/2019 MongoDB class by Alexandre Bergere 24
  • 25. Modelization 06/06/2019 MongoDB class by Alexandre Bergere 25
  • 26. Document are rich data structure • JSON: • String, Number, Array, Object, NULL, Boolean. • BSON: • Date, BinData, ObjectID, Geo-Location. • Better storage performance. ObjectID: ◦ _id : 'DATE[4] | MAC_ADDR[3] | PID[2] | COUNTER[3] 06/06/2019 MongoDB class by Alexandre Bergere 26
  • 27. Available Types Type Number Alias Notes Double 1 “double” String 2 “string” Object 3 “object” Array 4 “array” Binary data 5 “binData” Undefined 6 “undefined” Deprecated. ObjectId 7 “objectId” Boolean 8 “bool” Date 9 “date” Null 10 “null” RegularExpression 11 “regex” DBPointer 12 “dbPointer” Deprecated. JavaScript 13 “javascript” Symbol 14 “symbol” Deprecated. JavaScript (with scope) 15 “javascriptWithScope” 32-bit integer 16 “int” Timestamp 17 “timestamp” 64-bit integer 18 “long” Decimal128 19 “decimal” New in version 3.4. Min key -1 “minKey” Max key 127 “maxKey” 06/06/2019 MongoDB class by Alexandre Bergere 27
  • 28. Documents are Flexible 06/06/2019 MongoDB class by Alexandre Bergere 28
  • 29. Document Model Pers_ID Surname First_Name City 0 Miller Paul London 1 Ortega Alvaro Valencia 2 Huber Urs Zurich 3 Blanc Gaston Paris 4 Bertolini Fabrizio Rome Car_ID Model Year Value Pers_ID 101 Bently 1973 100000 0 102 Rolls Royce 1965 330000 0 103 Peugot 1993 500 3 104 Ferrari 2005 150000 4 105 Renault 1998 2000 3 106 Renault 2001 7000 3 107 Smart 1999 2000 2 CAR PERSON Mongo DB RDBMS 06/06/2019 MongoDB class by Alexandre Bergere 29
  • 30. TP - Modelization 1. Transform this address « 125 avenue de la république, 75011, PARIS » in BSON object. 2. Transform this 2 addresses « 125 avenue de la république, 75011, PARIS » and « 34 rue Ferdinand, 75012, PARIS » in an array. 3. Transform the schema below on BSON document. ID LastName FirstName Age 1 BERGERE Alexandre 26 Address ID People 125 avenue de la république, 75011, PARIS 1 34 rue Ferdinand, 75012, PARIS 1 1 n 06/06/2019 MongoDB class by Alexandre Bergere 30
  • 31. MongoDB - Starter 06/06/2019 MongoDB class by Alexandre Bergere 31
  • 32. SQL vs MongoDB Terms SQL Terms/Concepts MongoDB Terms/Concepts Database Database Table Collection Line Document Column Field Index Index Join Embeded or linked document Primary key Primary key (start by « _id ») 06/06/2019 MongoDB class by Alexandre Bergere 32
  • 33. Storage o MMAPv1 o WiredTiger o In Memory 06/06/2019 MongoDB class by Alexandre Bergere 33
  • 34. Installation 06/06/2019 MongoDB class by Alexandre Bergere 34
  • 35. Launch instance Launch as a service: o mongod --dbpath C:UsersalexaDocumentsMongoDBdata -- logpath C:UsersalexaDocumentMongoDBlogs.log Launch the conection: o mongo Launch a shard: o mongos Original Shortcut --db -d --collection -c --username -u --password -p --host -h Options: 06/06/2019 MongoDB class by Alexandre Bergere 35
  • 36. The Javascript console var authColl = db.getCollection("auth") authColl.insertOne( { usrName : "John Doe", usrDept : "Sales", usrTitle : "Executive Account Manager", authLevel : 4, authDept : [ "Sales", "Customers"] } ) 06/06/2019 MongoDB class by Alexandre Bergere 36
  • 37. DML 06/06/2019 MongoDB class by Alexandre Bergere 37
  • 38. DML # Returns all database > show dbs # The current database name: > db.getName() # Returns all database > show dbs # Returns all collection in the current database: > db.getCollectionNames() # Returns a collection or a view object: > db.getCollection(name) # The current database connection: > db.getMongo() # Clean the console log: > cls # Return collection informations: > db.getCollectionInfos({name: "name"}) 06/06/2019 MongoDB class by Alexandre Bergere 38
  • 39. DML # Removes the current database: > db.dropDatabase() # Copies a database to another database on the current host: >db.copyDatabase(fromdb, todb, fromhost, usern ame, password, mechanism) # Copies a database from a remote host to the current host: > db.cloneDatabase("hostname") # Rename collection: > db.renameCollection({ renameCollection: "fromCollection", to: " toCollection" }) > use test Or > db.orders.renameCollection( "toCollection" ) # Copies data directly between MongoDB instances: > db.cloneCollection(from, collection, query) 06/06/2019 MongoDB class by Alexandre Bergere 39
  • 40. Stats # Returns statistics that reflect the use state of a single database or collection. > db.stats() > db.collection.stats() { "ns" : "guidebook.restaurants", "count" : 25359, "size" : 10630398, "avgObjSize" : 419, "storageSize" : 4104192 "capped" : false, "wiredTiger" : { "metadata" : { "formatVersion" : 1 }, […] "nindexes" : 4, "totalIndexSize" : 626688, "indexSizes" : { "_id_" : 217088, "borough_1_cuisine_1" : 139264, "cuisine_1" : 131072, "borough_1_address.zipcode_1" : 139264 } 06/06/2019 MongoDB class by Alexandre Bergere 40
  • 41. Command-line tools Launch in the shell, not in mongoDB instance. 06/06/2019 MongoDB class by Alexandre Bergere 41
  • 42. Import or export document mongoexport and mongoimport: Export and import JSON, CSV, and TSV7 data. # Import multiples document: mongoimport -d crunchbase -c companies C:UsersalexaDocumentsMongoDBsrccompanies.json # Import multiples document in an array: mongoimport -d crunchbase -c artists --file C:UsersalexaDocumentsMongoDBsrcartists.json --jsonArray # Export collection: mongoexport --db crunchbase --collection artists --out artists.json 06/06/2019 MongoDB class by Alexandre Bergere 42
  • 43. Backup mongodump mongodump --host --port --db --username --password (when specifying the password as part of the URI connection string) --authenticationDatabase --authenticationMechanism # mongodump a Collection: mongodump --db test --collection collection # mongodump a Database: mongodump –archive=test.20100224.archive –db Crunchbase 06/06/2019 MongoDB class by Alexandre Bergere 43
  • 44. Restore mongostore mongostore --host --port --collection /pwd –db /pwd --db /pwd --username --password --authenticationDatabase <path to the backup> # Output an Archive to Standard Output: mongodump --archive --db test --port 27017 | mongorestore --archive --port 27018 06/06/2019 MongoDB class by Alexandre Bergere 44
  • 45. Others mongostore o mongosniff: A wire-sniffing tool for viewing operations sent to the database. It essentially translates the BSON going over the wire to human-readable shell statements. o mongostat: Similar to iostat, this utility constantly polls MongoDB and the system to provide helpful stats, including the number of operations per second (inserts, queries, updates, deletes, and so on), the amount of virtual memory allocated, and the number of connections to the server. o mongotop: Similar to top, this utility polls MongoDB and shows the amount of time it spends reading and writing data in each collection. o mongoperf: Helps you understand the disk operations happening in a running MongoDB instance. o mongooplog: Shows what’s happening in the MongoDB oplog. o Bsondump: Converts BSON files into human-readable formats including JSON. 06/06/2019 MongoDB class by Alexandre Bergere 45
  • 46. CRUD 06/06/2019 MongoDB class by Alexandre Bergere 46
  • 47. > create # Create a database > { create: <collection or view name>, capped: <true|false>, autoIndexId: <true|false>, size: <max_size>, max: <max_documents>, flags: <0|1|2|3>, storageEngine: <document>, validator: <document>, validationLevel: <string>, validationAction: <string>, indexOptionDefaults: <document>, viewOn: <source>, pipeline: <pipeline>, collation: <document> } 06/06/2019 MongoDB class by Alexandre Bergere 47
  • 48. Capped collection Distinguished from standard collectionsby their fixed size. This means that once a capped collection reaches its maximum size, subsequent inserts will overwrite the least-recently- inserted documents in the collection. This design prevents users from having to prune the collection manually when only recent data may be of value. > { create: <collection or view name>, capped: <true|false> […] } Designed for high-performance logging scenarios. 06/06/2019 MongoDB class by Alexandre Bergere 48
  • 49. > find # FIND() > db.<collection>.find ({<conditions>},{<champs>}) > db.products.find( { qty: { $gt: 25 } }, { item: 1, qty: 1 } ) sort, first, skip, second, and limit last because that is the only order that makes sense. # Options: > .pretty() .sort() : 1 : ASC, -1: DESC : sort({‘name’:-1}) .skip() : number .limit() : number .count() 06/06/2019 MongoDB class by Alexandre Bergere 49
  • 50. Partial Match Queries in Users # Use regular expression: > db.users.find({'last_name': /^Ber/}) 06/06/2019 MongoDB class by Alexandre Bergere 50
  • 51. > insert # INSERT() > db.<collection>.insert ({<value>}) > db.<collection>.insertMany([{<values>}]) > db.inventory.insertMany([ { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } }, { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } }, { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } } ]) db.collection.insertOne() Inserts a single document into a collection. db.collection.insertMany() db.collection.insertMany() inserts multiple documents into a collection. db.collection.insert() db.collection.insert() inserts a single document or multiple documents into a collection. 06/06/2019 MongoDB class by Alexandre Bergere 51
  • 52. > update # UPDATE() > db.<collection>.update ({<conditions>},{<champs>},{upsert:true/false},{multi:true/false} ) > { "_id": "artist:281", "last_name": "Cotillard", "first_name": "Marion", "birth_date": "1975" } # Operator Update: > db.artists.update({"_id": "artist:281"},{ $set : {"last_name" : "Page"}}) > { "_id": "artist:281", "last_name": “Page", "first_name": "Marion", "birth_date": "1975" } # Replacement Update: > db.artists.update({"_id": "artist:281"},{"last_name" : "Page"}) > { "_id": "artist:281", "last_name": “Page"} ❑ Operator Update ❑ Replacement Update All updates require at least two arguments. The first specifies which documents to update, and the second defines how the selected documents should be modified 06/06/2019 MongoDB class by Alexandre Bergere 52
  • 53. > update Upsert: boolean Optional. If set to true, creates a new document when no document matches the query criteria. The default value is false, which does not insert a new document when no match is found. Multi: boolean Optional. If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document. The default value is false. # UPDATE() > db.<collection>.update ({<conditions>},{<champs>} ,{upsert:true/false} ,{multi:true/false} ) > db.pageview.update({'_id':'/potager/users'},{$inc:{'views':1}},{upsert:true}) 06/06/2019 MongoDB class by Alexandre Bergere 53
  • 54. Query Operator Name Description $eq Matches values that are equal to a specified value. $gt Matches values that are greater than a specified value. $gte Matches values that are greater than or equal to a specified value. $lt Matches values that are less than a specified value. $lte Matches values that are less than or equal to a specified value. $ne Matches all values that are not equal to a specified value. $in Matches any of the values specified in an array. 06/06/2019 MongoDB class by Alexandre Bergere 54
  • 55. Query Operator Name Description $set Sets the value of a field in a document. $unset Removes the specified field from a document. $inc Increments a field by a specified value. $rename updates the name of a field $muc Multiply the value of a field by a number > db.products.update( { _id: "56c0befa5e435acc1d4a5fbd"}, { $inc: { quantity: -2} }) 06/06/2019 MongoDB class by Alexandre Bergere 55
  • 56. Query Operator : $set # $set > db.products.update( { _id: 100 }, { $set: { quantity: 500, details: { model: "14Q3", make: "xyz" }, tags: [ "coats", "outerwear", "clothing" ] } } ) # $set Embedded Documents > db.products.update( { _id: 100 }, { $set: { "details.make": "zzz" } } ) # $set in Arrays > db.products.update( { _id: 100 }, { $set: { "tags.1": "rain gear", "ratings.0.rating": 2 } } ) 06/06/2019 MongoDB class by Alexandre Bergere 56
  • 57. Array { _id: 1, fruits: [ "apples", "pears", "oranges", "grapes", "bananas" ], vegetables: [ "carrots", "celery", "squash", "carrots" ] } { _id: 2, fruits: [ "plums", "kiwis", "oranges", "bananas", "apples" ], vegetables: [ "broccoli", "zucchini", "carrots", "onions" ] } > db.stores.update( { }, { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } }, { multi: true } ) 06/06/2019 MongoDB class by Alexandre Bergere 57
  • 58. Query Operator : Arrays Name Description $set Sets the value of a field in a document. $unset Removes the specified field from a document. $inc Increments a field by a specified value. $rename updates the name of a field $muc Multiply the value of a field by a number > db.products.update( { _id: "56c0befa5e435acc1d4a5fbd"}, { $inc: { quantity: -2} }) 06/06/2019 MongoDB class by Alexandre Bergere 58
  • 59. > delete # DELETE() > db.<collection>.remove ({<conditions>}) > db.artists.remove({"_id": "artist:39"}) # Remove all fields > db.artists.remove({}) 06/06/2019 MongoDB class by Alexandre Bergere 59
  • 60. TP - Modelization 1. Import the json document “veg_garden” into mongoDB. 2. Return all vegetable garden with an existing property of “number”. 3. Return all vegetable garden with an existing property of “harvest”. 4. Return all vegetable garden with a service’ title “Classes”. 5. Return all vegetable garden with a sale’s address number 52. 6. Return all vegetable garden that have the product 97. 7. Import json documents “companies” and “artists” into mongoDB. 8. Return the number of companies with a number of employees less or equal to 45. 9. Return artists from the 6th to the 9th ordered desc by their name. 10. Insert the following artist: "_id": "artist:9", "last_name": "Bergere", "first_name": "Alexandre", "birth_date": "1992“. 11. Add « golf » on artist’s hobbies with the id 280. 12. Add « yoga » on artist’s hobbies with the id 282. 13. Delete hobbies « pony » and « painting » from the artist 280. 06/06/2019 MongoDB class by Alexandre Bergere 60
  • 61. TP - Modelization # 1. Import the json document “veg_garden” into mongoDB. mongoimport -d crunchbase -c vegGarden --file C:UsersalexCoursMongoDB2018-2019srcveg_garden.json -- jsonArray # 2. Return all vegetable garden with an existing property of “number”. > db.vegGarden.find({"number":{$exists:true}}).pretty() # 3. Return all vegetable garden with an existing property of “harvest”. > db.vegGarden.find({"harvest":{$exists:true}}).pretty() # 4. Return all vegetable garden with a service’s title “Classes”. > db.vegGarden.find({"service.title":“Classes"}).pretty() # 5. Return all vegetable garden with a sale’s address number 52. > db.vegGarden.find({"adresse.sale.num":52}).pretty() # 6. Delete hobbies « pony » and « painting » from the artist 280. > db.vegGarden.find({"products":{$in:[97]}}) 06/06/2019 MongoDB class by Alexandre Bergere 61
  • 62. TP - Modelization # 7. Import json documents “companies” and “artists” into mongoDB. mongoimport -d crunchbase -c artists --file C:UsersalexCoursMongoDB2018-2019srcartists.json -- jsonArray mongoimport -d crunchbase -c companies C:UsersalexCoursMongoDB2018-2019srccompanies.json # 8. Return the number of companies with a number of employees less or equal to 45. > db.companies.count({number_of_employees:{$lte:45}}) # 9. Return artists from the 6th to the 9th ordered desc by their name > db.artists.find().pretty().sort({"last_name":-1}).skip(5).limit(4) # 10. Insert the following artist: "_id": "artist:9", "last_name": "Bergere", "first_name": "Alexandre", "birth_date": "1992" . Remplacer le numéro d’id par 282. > db.artists.insert({ "_id": "artist:9", "last_name": "Bergere", "first_name": "Alexandre", "birth_date": "1992" }) # 11. Add « golf » on artist’s hobbies with the id 280. > db.artists.update({"_id": "artist:280"},{$push:{"hobbies":"golf"}}) # 12. Add « yoga » on artist’s hobbies with the id 282. > db.artists.update({"_id": "artist:282"},{$push:{"hobbies":"yoga"}}) # 13. Retirer les hobbies « poney » et « photo » à l’artiste 280. > db.artists.update({"_id": "artist:280"},{$pull:{"hobbies": {$in:["pony","photo"]}}}) 06/06/2019 MongoDB class by Alexandre Bergere 62
  • 63. Schema Validation 06/06/2019 MongoDB class by Alexandre Bergere 63
  • 64. Schema validation • Implement data governance without sacrificing the agility that comes from a dynamic schema. • With schema validation, developers and operations spend less time defining data quality controls in their applications, and instead delegate these tasks to the database. To specify validation rules when creating a new collection, use with the valid db.createCollection() option. To add document validation to an existing collection, use collMod command with the validator option. 06/06/2019 MongoDB class by Alexandre Bergere 64
  • 65. Example of schema validation # Create a database > db.createCollection("students", { validator: { $jsonSchema: { bsonType: "object", required: [ "name", "year", "major", "gpa" ], additionalProperties: true, properties: { name: { bsonType: "string", description: "must be a string and is required" }, gender: { bsonType: "string", description: "must be a string and is not required" }, year: { bsonType: "int", minimum: 2017, maximum: 3017, exclusiveMaximum: false, description: "must be an integer in [ 2017, 3017 ] and is required" } > […] major: { enum: [ "Math", "English", "Computer Science", "History", null ], description: "can only be one of the enum values and is required" }, gpa: { bsonType: [ "double" ], minimum: 0, description: "must be a double and is required" } } } } }) 06/06/2019 MongoDB class by Alexandre Bergere 65
  • 66. Query expression In addition to JSON Schema validation, MongoDB supports validation with query filter expressions using the query operators, with the exception of $near, $nearSphere, $text, and $where. > db.createCollection( "contacts", { validator: { $or: [ { phone: { $type: "string" } }, { email: { $regex: /@mongodb.com$/ } }, { status: { $in: [ "Unknown", "Incomplete" ] } } ] } } ) 06/06/2019 MongoDB class by Alexandre Bergere 66
  • 67. Add a validator to an existing collection In addition to JSON Schema validation, MongoDB supports validation with query filter expressions using the query operators, with the exception of $near, $nearSphere, $text, and $where. > db.runCommand( { collMod: "contacts", validator: { $jsonSchema: { bsonType: "object", required: [ "phone", "name" ], properties: { phone: { bsonType: "string", description: "must be a string and is required" }, name: { bsonType: "string", description: "must be a string and is required" } } } }, validationLevel: "moderate" } ) collMod 06/06/2019 MongoDB class by Alexandre Bergere 67
  • 68. Validation level & action ValidationLevel Description "off" disable validation entirely. "strict" If the validationLevel is strict (the default), MongoDB applies validation rules to all inserts and updates. "moderate" If the validationLevel is moderate, MongoDB applies validation rules to inserts and to updates to existing documents that already fulfil the validation criteria. With the moderate level, updates to existing documents that do not fulfill the validation criteria are not checked for validity. validationAction Description "error" Default Documents must pass validation before the write occurs. Otherwise, the write operation fails. "warn" Documents do not have to pass validation. If the document fails validation, the write operation logs the validation failure. ValidationLevel option, which determines how strictly MongoDB applies validation rules to existing documents during an update. ValidationAction option, which determines whether MongoDB should error and reject documents that violate the validation rules or warn about the violations in the log but allow invalid documents. 06/06/2019 MongoDB class by Alexandre Bergere 68
  • 69. Bypass Document Validation Users can bypass document validation on commands and methods that support the bypassDocumentValidation option. The following commands and their equivalent methods support bypassing document validation: oaggregate oapplyOps ocloneCollection on the destination collection oclone on the destination ocopydb on the destination ofindAndModify oinsert omapReduce oUpdate For deployments that have enabled access control, to bypass document validation, the authenticated user must have bypassDocumentValidation action. The built-in roles dbAdmin and restore provide this action. 06/06/2019 MongoDB class by Alexandre Bergere 69
  • 70. TP – Schema Validation 1. Add the following schema validation to the artists’ collection: • "last_name","first_name","status" required. • “status” can take only this two values: "alive“ or "dead" 2. Try to insert the following artist: { "last_name": "Katerine", "first_name": "Philippe"} 3. Update the artist with the id “artists:281”, by modify his name by “Kheirona”. 4. Change validation level in « moderate ». 5. Try again the update in question 3. 6. Change validation action in « warn », then insert again the artist in question 2. 06/06/2019 MongoDB class by Alexandre Bergere 70
  • 71. TP – Schema Validation # 1. Add the following schema validation to the artists’ collection: > db.runCommand({ collMod: "artists", validator:{ $jsonSchema:{ bsonType: "object", required:["last_name","first_name","status"], properties:{ last_name:{ bsonType: "string", description:"must be a string and is required" } ,first_name:{ bsonType: "string", description:"must be a string and is required" } ,status:{ enum: ["alive", "dead"], description:"must be a alive or dead and is required" } } }, } ,validationLevel: "strict" }) 06/06/2019 MongoDB class by Alexandre Bergere 71
  • 72. TP – Schema Validation # 1. Option 2: > db.runCommand({ collMod: "artists", validator:{ $and: [ { last_name: { $type: "string" } }, { first_name: { $type: "string" } }, { status: { $in: [ "alive", "dead" ] } } ], $jsonSchema:{ required:["last_name","first_name","status"] }, } ,validationLevel: "strict" }) 06/06/2019 MongoDB class by Alexandre Bergere 72
  • 73. TP – Schema Validation # 2. Try to insert the following artist: { "last_name": "Katerine", "first_name": "Philippe"} > db.artists.insert({ "last_name": "Katerine", "first_name": "Philippe"}) – {failed} # 3. Update the artist with the id “artists:281”, by modify his name by “Kheirona”. > db.artists.update({"_id": "artist:281"},{ $set:{ "last_name": " Kheirona" }}) # 4. Change validation level in « moderate ». > db.runCommand({ collMod: "artists" ,validationLevel : "moderate" }) # 6. Change validation action in « warn », then insert again the artist in question 2. db.runCommand({ collMod: "artists" ,validationAction: "warn" }) 2018-12-01T12:31:23.738-0500 W STORAGE [conn1] Document would fail validation collection: example.contacts2 doc: { _id: ObjectId('5a2191ebacbbfc2bdc4dcffc’), last_name: " Kheirona "} 06/06/2019 MongoDB class by Alexandre Bergere 73
  • 74. One to many 06/06/2019 MongoDB class by Alexandre Bergere 74
  • 75. One to N One to few 06/06/2019 MongoDB class by Alexandre Bergere 75
  • 76. One to N One to many 06/06/2019 MongoDB class by Alexandre Bergere 76
  • 77. One to N { _id: ObjectId("6a5b1476238d3b4dd5000048"), slug: "gardening-tools", name: "Gardening Tools", description: "Gardening gadgets galore!", parent_id: ObjectId("55804822812cb336b78728f9"), ancestors: [ { name: "Home", _id: ObjectId("558048f0812cb336b78728fa"), slug: "home" }, { name: "Outdoors", _id: ObjectId("55804822812cb336b78728f9"), slug: "outdoors" } ] } > db.products.find({category_ids: ObjectId('6a5b1476238d3b4dd5000048')}) 06/06/2019 MongoDB class by Alexandre Bergere 77
  • 78. One to N { _id: ObjectId("6a5b1476238d3b4dd5000048"), slug: "gardening-tools", name: "Gardening Tools", description: "Gardening gadgets galore!", parent_id: ObjectId("55804822812cb336b78728f9"), ancestors: [ { name: "Home", _id: ObjectId("558048f0812cb336b78728fa"), slug: "home" }, { name: "Outdoors", _id: ObjectId("55804822812cb336b78728f9"), slug: "outdoors" } ] } # $set in Arrays > db.products.find({category_ids: ObjectId('6a5b1476238d3b4dd5000048')}) # To query for all categories from a given product: > var product = db.products.findOne({"slug": "wheelbarrow-9092"}) > db.categories.find({_id: {$in: product['category_ids']}}) 06/06/2019 MongoDB class by Alexandre Bergere 78
  • 79. TP – One to Many Student Subject 06/06/2019 MongoDB class by Alexandre Bergere 79
  • 80. TP – One to Many # Student: > db.student.insertMany([ { "name":"bergere", "surname":"alex", "subject":[ { "id_ subject": "MongoDB" ,"note" : [15,13] }, { "id_subject": "NodeJS" ,"note" : [12,13] } ] }, { "name":"Fauchard", "surname":"Than Tuan", "subject":[ { "id_ subject": "MongoDB" ,"note" : [12,18] }, { "id_subject": "NodeJS" ,"note" : [15,8] } ] } ]) 06/06/2019 MongoDB class by Alexandre Bergere 80
  • 81. TP – One to Many # Subject: > db.subject.insertMany([ { "_id":"MongoDB" ,"nom":"MongoDB" ,"salle":"A09" ,"prof":"Alexandre Bergere" }, { "_id":"NodeJS" ,"nom":"NodeJS" ,"salle":"A12" ,"prof":"Thierry Dupont" } ]) 06/06/2019 MongoDB class by Alexandre Bergere 81
  • 82. TP – One to Many # Request: > var subject = [] > db.subject.find().forEach(function(u) { subject.push(u._id) }) > db.student.find({"subject.id_ subject": {$in: subject}}) 06/06/2019 MongoDB class by Alexandre Bergere 82
  • 83. TP – Many to Many Student Subject 06/06/2019 MongoDB class by Alexandre Bergere 83
  • 84. TP – Many to Many # Student: > db.student.insertMany([ { "_Id" : ObjectID("23109834091209"), "name":"bergere", "surname":"alex", "subject":[ { "id_ subject": "MongoDB" ,"note" : [15,13] }, { "id_subject": "NodeJS" ,"note" : [12,13] } ] }, { "_Id" : ObjectID("97099230912812"), "name":"Fauchard", "surname":"Than Tuan", "subject":[ { "id_ subject": "MongoDB" ,"note" : [12,18] }, { "id_subject": "NodeJS" ,"note" : [15,8] } ] } 06/06/2019 MongoDB class by Alexandre Bergere 84
  • 85. TP – Many to Many # Subject: > db.subject.insertMany([ { "_id":"MongoDB" ,"nom":"MongoDB" ,"salle":"A09" ,"prof":"Alexandre Bergere" ,"Students":[ { "Prom":"ir2016", "Student_id":[ObjectID("97099230912812"), ObjectID("23109834091209")] } ] }, { "_id":"NodeJS" ,"nom":"NodeJS" ,"salle":"A12" ,"prof":"Thierry Dupont" ,"Students":[ { "Prom":"ir2016", "Student_id":[ObjectID("97099230912812"), ObjectID("23109834091209")] } ] } ]) 06/06/2019 MongoDB class by Alexandre Bergere 85
  • 86. $lookup > { $lookup: { from: <collection to join>, localField: <field from the input documents>, foreignField: <field from the documents of the "from" collection>, as: <output array field> } } 06/06/2019 MongoDB class by Alexandre Bergere 86
  • 87. $lookup db.orders.insert([ { "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 }, { "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 }, { "_id" : 3 } ]) db.inventory.insert([ { "_id" : 1, "sku" : "almonds", description: "product 1", "instock" : 120 }, { "_id" : 2, "sku" : "bread", description: "product 2", "instock" : 80 }, { "_id" : 3, "sku" : "cashews", description: "product 3", "instock" : 60 }, { "_id" : 4, "sku" : "pecans", description: "product 4", "instock" : 70 }, { "_id" : 5, "sku": null, description: "Incomplete" }, { "_id" : 6 } ]) 06/06/2019 MongoDB class by Alexandre Bergere 87
  • 88. $lookup > db.orders.aggregate([ { $lookup: { from: "inventory", localField: "item", foreignField: "sku", as: "inventory_docs" } } ]) { "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2, "inventory_docs" : [ { "_id" : 1, "sku" : "almonds", "description" : "product 1", "instock" : 120 } ] } { "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1, "inventory_docs" : [ { "_id" : 4, "sku" : "pecans", "description" : "product 4", "instock" : 70 } ] } { "_id" : 3, "inventory_docs" : [ { "_id" : 5, "sku" : null, "description" : "Incomplete" }, { "_id" : 6 } ] }06/06/2019 MongoDB class by Alexandre Bergere 88
  • 89. TP – $lookup # Subject: > db.subject.aggregate([ { $lookup: { from: "student", localField: "_id", foreignField: "subject.id_ subject", as: "student" } } ]) # Student: > db.student.aggregate([ { $lookup: { from: "subject", localField: "subject.id_ subject", foreignField: "_id", as: "description" } } ]) 06/06/2019 MongoDB class by Alexandre Bergere 89
  • 90. Index 06/06/2019 MongoDB class by Alexandre Bergere 90
  • 91. Index Indexes are special data structures [1] that store a small portion of the collection’s data set in an easy to traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field. The ordering of the index entries supports efficient equality matches and range-based query operations. In addition, MongoDB can return sorted results by using the ordering in the index. 06/06/2019 MongoDB class by Alexandre Bergere 91
  • 92. Index # Create > db.collection.createIndex({'name':1}) # Get > db.collection.getIndexes() # Delete > db.collection.dropIndex({'name':1}) 06/06/2019 MongoDB class by Alexandre Bergere 92
  • 93. $text 06/06/2019 MongoDB class by Alexandre Bergere 93
  • 94. $text $text performs a text search on the content of the fields indexed with a text index. A $text expression has the following syntax: { $text: { $search: <string>, $language: <string>, $caseSensitive: <boolean>, $diacriticSensitive: <boolean> } } > db.articles.find( { $text: { $search: "coffee" } } ) 06/06/2019 MongoDB class by Alexandre Bergere 94
  • 95. $text - indexation Indexes A collection can have at most one text index. > db.collection.createIndex( { comments: "text" } ) # You can index multiple fields for the text index: > db.collection.createIndex( { subject: "text", comments: "text" } ) First, create your index ! Wildcard Text Indexes When creating a text index on multiple fields, you can also use the wildcard specifier ($**). With a wildcard text index, MongoDB indexes every field that contains string data for each document in the collection. The following example creates a text index using the wildcard specifier: db.collection.createIndex( { "$**": "text" } ) 06/06/2019 MongoDB class by Alexandre Bergere 95
  • 96. $text Case Insensitivity The version 3 text index supports the common C, simple S, and for Turkish languages, the special T case foldings as specified in Unicode 8.0 Character Database Case Folding. The case foldings expands the case insensitivity of the text index to include characters with diacritics, such as é and É, and characters from non-Latin alphabets, such as “И” and “и” in the Cyrillic alphabet. Version 3 of the text index is also diacritic insensitive. As such, the index also does not distinguish between é, É, e, and E. Previous versions of the text index are case insensitive for [A-z] only; i.e. case insensitive for non-diacritics Latin characters only . For all other characters, earlier versions of the text index treat them as distinct. 06/06/2019 MongoDB class by Alexandre Bergere 96
  • 97. $text - indexation Case Insensitivity Match Any of the Search Terms If the search string is a space-delimited string, $text operator performs a logical OR search on each term and returns documents that contains any of the terms. Search for a Phrase To match the exact phrase as a single term, escape the quotes. Exclude Documents That Contain a Term A negated term is a term that is prefixed by a minus sign -. If you negate a term, the $text operator will exclude the documents that contain those terms from the results. Search a Different Language Use the optional $language field in the $text expression to specify a language that determines the list of stop words and the rules for the stemmer and tokenizer for the search string. If you specify a language value of "none", then the text search uses simple tokenization with no list of stop words and no stemming. > db.articles.find( { $text: { $search: "bake coffee cake" } } ) > db.articles.find( { $text: { $search: ""coffee shop"" } } ) > db.articles.find( { $text: { $search: "coffee -shop" } } ) > db.articles.find({ $text: { $search: "leche", $language: "es" } }) 06/06/2019 MongoDB class by Alexandre Bergere 97
  • 98. TP – $text 1. Find in collection « companies » the following words: “Server” & “Software” in the fields “description” and “name”. 06/06/2019 MongoDB class by Alexandre Bergere 98
  • 99. TP – $text # Request: > db.companies.createIndex( { name: "text", description: "text" } ) > db.companies.find( { $text: { $search: "Server Software" } } ) > db.companies.find( { $text: { $search: "Server Software" } }, {'description':1,'name':1} ).pretty() 06/06/2019 MongoDB class by Alexandre Bergere 99
  • 100. Compass 06/06/2019 MongoDB class by Alexandre Bergere 100
  • 101. MongoDB Compass 06/06/2019 MongoDB class by Alexandre Bergere 101
  • 102. MongoDB Compass 06/06/2019 MongoDB class by Alexandre Bergere 102
  • 103. MongoDB Compass 06/06/2019 MongoDB class by Alexandre Bergere 103
  • 104. MongoDB Compass Visualize, understand, and work with your geospatial data Point and click to construct sophisticated queries, execute them with the push of a button and Compass will display your results both graphically and as sets of JSON documents. A better approach to CRUD makes it easier to interact with your data Modify existing documents with greater confidence using the intuitive visual editor, or insert new documents and clone or delete existing ones in just a few clicks. 06/06/2019 MongoDB class by Alexandre Bergere 104
  • 105. MongoDB Compass Compass Community Editions View, add, and delete databases and collections X X View and interact with documents with full CRUD functionality X X Build and run ad hoc queries X X View and optimize query performance with visual explain plans X X Manage indexes: view stats, create, and delete X X Create and execute aggregation pipelines X X Kerberos, LDAP and x509 Authentication X Schema Analysis X Real Time Server Stats X Document Validation X 06/06/2019 MongoDB class by Alexandre Bergere 105
  • 106. MongoDB Compass Compass Readonly Edition New in version 1.12.0 A read-only version of MongoDB Compass is available which provides the ability to limit certain CRUD operations within your organization. In this version, users are limited strictly to read operations within MongoDB. Compass Isolated Edition New in version 1.14.0 Compass Isolated Edition restricts network requests to TLS-encrypted TCP connections to the server chosen on the Connect screen. All other outbound connections are not permitted in this edition. 06/06/2019 MongoDB class by Alexandre Bergere 106
  • 107. TP - Compass 1. Insert the following artist: {“last_name”: “Van gogh”, "first_name": “Vincent”} 2. Add hobbies “pony” and “painting” to the artist 280. 3. Add "birth_date" to the schema validation. 4. Return artists from the 6th to the 9th ordered desc by their name. 5. Free test 06/06/2019 MongoDB class by Alexandre Bergere 107 Artist collection:
  • 108. Hackolade 06/06/2019 MongoDB class by Alexandre Bergere 108
  • 109. Hackolade 06/06/2019 MongoDB class by Alexandre Bergere 109
  • 110. Replica set 06/06/2019 MongoDB class by Alexandre Bergere 110
  • 111. Replica Set A replica set in MongoDB is a group of mongod processes that maintain the same data set. Replica sets provide redundancy and high availability, and are the basis for all production deployments. This section introduces replication in MongoDB as well as the components and architecture of replica sets. The section also provides tutorials for common tasks related to replica sets. Replication provides redundancy and increases data availability. With multiple copies of data on different database servers, replication provides a level of fault tolerance against the loss of a single database server. In some cases, replication can provide increased read capacity as clients can send read operations to different servers. Maintaining copies of data in different data centers can increase data locality and availability for distributed applications. You can also maintain additional copies for dedicated purposes, such as disaster recovery, reporting, or backup 06/06/2019 MongoDB class by Alexandre Bergere 111
  • 112. Replica set 27017 27018 27019 Primary Arbiter Secondary REPLICATION Types de serveur: • primary • secondary • arbiter • hidden 06/06/2019 MongoDB class by Alexandre Bergere 112
  • 113. Replica set 06/06/2019 MongoDB class by Alexandre Bergere 113
  • 114. Replica set options mongod --port 27001 --replSet name --dbpath paht of data --logpath user --logappend (if the server shutdown) --oplogSize 50 mongod --port 27017 --dbpath "C:UsersalexaDocumentsMongoDBdata_primary" --replSet rs0 -- smallfiles --oplogSize 128 mongod --port 27018 --dbpath "C:UsersalexaDocumentsMongoDBdata_secondary" --replSet rs0 -- smallfiles --oplogSize 128 mongod --port 27019 --dbpath "C:UsersalexaDocumentsMongoDBdata_arbitrer" --replSet rs0 -- smallfiles --oplogSize 128 06/06/2019 MongoDB class by Alexandre Bergere 114
  • 115. Replica set Replica Options: • arbitrerOnly : true (à aucunes données et permet de voter lors d'un nombre paire de serveur) • priority : 0 (never primary) permet de donner un ordre sur le futur primary en cas de problèmes • hidden : true permet de cacher le serveur des clients, il ne peut être primary • slaveDelay : Mets à jour les data avec un delay (ex : 8*3600 récupère les données avec toujours 8h de retard) (rajouter hidden:true) • vote : 2 (ex) permet de rajouter des votes (déconseiller, autant utiliser arbiterOnly) [ex : Srv 1 (vote 2) Srv 2 (vote 1) si Srv tombe, Srv2 a 1/3, il devient pas primary] 06/06/2019 MongoDB class by Alexandre Bergere 115
  • 116. Replica set Initialisation # Use rs.initiate() on one and only one member of the replica set: > rs.initiate({ _id: "rs0", version: 1, members: [ { _id: 0, host : "localhost:27017" } , { _id: 1, host : "localhost:27018" } ] } ) # Add other replica: > rs.add("localhost:27018") > rs.addArb(" localhost :27019") # Delete a server from the replicaSet: > rs.remove("localhost:27018") # Check the configuration: > rs.conf() 06/06/2019 MongoDB class by Alexandre Bergere 116
  • 117. Replica set Command # In each Replica: > rs.slaveOk() # Check status: > rs.status() The secondary only accepts writes that it gets through replication. To allow queries on a secondary, we must tell Mongo that we are okay with reading from the secondary. 06/06/2019 MongoDB class by Alexandre Bergere 117
  • 118. Replica set Reconfiguration # For the hidden: > cfg = rs.conf() > cfg.members[2].priority = 0 > cfg.members[2]. slaveDelay = 86400 > cfg.members[2].hidden = true > rs.reconfig(cfg) # For the hidden: > rs.remove("localhost:27018") > rs.addArb("localhost :27018") To do only on the PRIMARY ! 06/06/2019 MongoDB class by Alexandre Bergere 118
  • 119. Fire & Forget strategy You can configure MongoDB to fire-and-forget, sending off a write to the server without waiting for an acknowledgment. For high-volume, low-value data (like clickstreams and logs), fire-and-forget-style writes can be ideal. You can also configure MongoDB to guarantee that a write has gone to multiple replicas before considering it committed. For important data, a safe mode setting is necessary. 06/06/2019 MongoDB class by Alexandre Bergere 119
  • 120. TP – Replica set 1. Init 3 replicas. 2. Import the dump on the primary. 3. Put one of the replicas in backup, adjust its reception delay to 24h. 4. Try to insert data into a secondary. 5. Insert data into the primary and check its persistence on the network. 6. Add a fourth replica and configure it as an arbiter (check data behaviour on this one). 7. Import the file “place.json”. Is it persistent on all the network? 8. Set the priority to 2 for the primary, shutdown it and start it back. 06/06/2019 MongoDB class by Alexandre Bergere 120
  • 121. TP – Replica set 06/06/2019 MongoDB class by Alexandre Bergere 121 # 1. Init 3 replica: mongod --port 27017 --dbpath C:UsersalexaDocumentsCoursMongoDB2018-2019data1 --replSet rs0 -- smallfiles --oplogSize 128 mongod --port 27018 --dbpath C:UsersalexaDocumentsCoursMongoDB2018-2019data2 --replSet rs0 -- smallfiles --oplogSize 128 mongod --port 27019 --dbpath C:UsersalexaDocumentsCoursMongoDB2018-2019data3 --replSet rs0 -- smallfiles --oplogSize 128 mongo --port 27017 > rs.initiate() > rs.conf() > rs.add("localhost:27018") > rs.add("localhost:27019") mongo --port 27018 > rs.slaveOk() mongo --port 27018 > rs.slaveOk()
  • 122. TP – Replica set 06/06/2019 MongoDB class by Alexandre Bergere 122 # 2. Import the dump on the primary: mongodump --archive --db crunchbase --port 27058 | mongorestore --archive --port 27017 # 3. Put one of the replicas in backup, adjust its reception delay to 24h: > cfg = rs.conf() > cfg.members[2].priority = 0 > cfg.members[2].hidden = true > rs.reconfig(cfg) # 6. Add a fourth replica and configure it as an arbiter (check data behaviour on this one): mongod --port 27020 --dbpath C:UsersalexaDocumentsCoursMongoDB2018-2019data4 --replSet rs0 -- smallfiles --oplogSize 128 mongo --port 27017 > rs.addArb("localhost:27020") mongo --port 27020 > rs.slaveOk()
  • 123. TP – Replica set 06/06/2019 MongoDB class by Alexandre Bergere 123 # 7. Set the priority to 2 for the primary, shutdown it and start it back: > cfg = rs.conf() > cfg.members[3].priority = 2 > rs.reconfig(cfg)
  • 124. Aggregation 06/06/2019 MongoDB class by Alexandre Bergere 124
  • 125. Aggregation Swiss Army knife Executes in native code o Written in C++ o JSON parameter Flexible, funcional, simple o Operation pipeline o Computational expressions 06/06/2019 MongoDB class by Alexandre Bergere 125
  • 126. Aggregation Operator Description $match Filter documents $project Reshape documents $group Summarize documents $unwind Expand arrays in documents $sort Order documents $limit / $skip Paginate documents $redact Restrict documents $geoNear Proximity sort documents $let, $map Define variables 06/06/2019 MongoDB class by Alexandre Bergere 126
  • 127. $match # Matching field values > {$match:{ language:"Russian" } { title:"War and Peace", pages:1440, language:"Russian" } # Matching with query operators > {$match:{ pages:{$gt:100} } { title:"War and Peace", pages:1440, language:"Russian" }, { title:"Atlas Shrugged", pages:1088, language:"English" } 06/06/2019 MongoDB class by Alexandre Bergere 127
  • 128. $project # Renaming and computing fields > {$project:{ avgChapterLength:{ $divide:["$pages", "$chapters" ] }, lang: "$language" }} { _id:375, avgChapterLength: 24,2222 lang:"English" } # Including & excluding fields > {$project:{ _id:0, title:1, language:1 }} { title:"Great Gatsby" , language:"English" } 06/06/2019 MongoDB class by Alexandre Bergere 128
  • 129. $group # Collect distinct values > {$group:{ _id:"$langugage", titles:{$addToSet:"$title"} }} { _id:"English", titles:["Atlas Shrugged" , "The Great Gatsby"] }, { _id:"Russian", titles:["War and Peace"] } # Calculating average, summing fields… > {$group:{ _id:"$langugage", pages:{$sum:"$pages"}, books:{$sum:1}, avgPages:{$avg:"$pages"} }} { _id:"Russian", pages:1440, books:1, avgPages:1440 } 06/06/2019 MongoDB class by Alexandre Bergere 129
  • 130. $unwind # Collect distinct values > {$unwind:{ "subjects" } { title:"The Great Gatsby", ISBN:"9762832930920323" , subjects:"Long Island" }, { title:"The Great Gatsby", ISBN:"9762832930920323" , subjects:"New York" }, { title:"The Great Gatsby", ISBN:"9762832930920323" , subjects:"1920s" } { title:"The Great Gatsby", ISBN:"9762832930920323" , subjects:[ "Long Island", "New York", "1920s" ] } 06/06/2019 MongoDB class by Alexandre Bergere 130
  • 131. TP - Aggregation 1. How many companies has more than 999 employees and was founded in or after 2000? 2. Number of companies and Number of employees group by founded year, ordrer by founded_year desc? 3. How many companies group by category_code, with a list of all included companies names, with category_code filter on medical or government? 4. How many companies has more than 1000 employees and was founded after 2000 (with agg. function)? 06/06/2019 MongoDB class by Alexandre Bergere 131
  • 132. TP - Aggregation 06/06/2019 MongoDB class by Alexandre Bergere 132 # 1. How many companies has more than 1000 employees and was founded after 2000? > db.companies.count({$and:[{"number_of_employees":{$gte:1000}},{"founded_year":{$gte:2000}}]},{}) # 2. Number of companies and Number of employees group by founded year, order by founded_year desc? > db.companies.aggregate ([ { $sort : { founded_year: 1} }, { "$group" : { "_id" : "$founded_year", "NumberOfCompanies" : {$sum : 1}, "NumberOfEmployees":{$sum : "$number_of_employees"} } } ]).pretty()
  • 133. TP - Aggregation 06/06/2019 MongoDB class by Alexandre Bergere 133 # 3. How many companies group by category_code, with a list of all included companies names, with category_code filter on medical or government? > db.companies.aggregate ([ { "$match":{ category_code: {$in:["medical","government"]} } }, { "$group" : { "_id" : "$category_code", "NumberOfCompanies" : {"$sum" : 1}, "Companies":{$addToSet:"$name"} } } ]).pretty()
  • 134. TP - Aggregation 06/06/2019 MongoDB class by Alexandre Bergere 134 # 4. How many companies has more than 1000 employees and was founded after 2000 (with agg. function)? > db.companies.aggregate ([ { "$match":{ $and:[{"number_of_employees":{$gte:1000}},{"founded_year":{$gte:2000}}] } }, { "$group" : { "_id" : null, "NumberOfCompanies" : {"$sum" : 1} } } ]).pretty() > db.companies.aggregate ([ { "$match":{ $and:[{"number_of_employees":{$gte:1000}},{"founded_year":{$gte:2000}}] } }, { "$count" : "NumberOfCompanies" } ]).pretty()
  • 135. Authentification 06/06/2019 MongoDB class by Alexandre Bergere 135
  • 136. Authentication vs Authorization Authentification Authorization Verify the identity of a user. Verify the privileges of a user. 06/06/2019 MongoDB class by Alexandre Bergere 136
  • 137. Authentification Client/User Auth SCRAM-SHA-1 MONGODB-CR X.509 LDAP Kerberos Internal Auth Keyfile (SCRAM-SHA-1) X.509 Community Enterprise 06/06/2019 MongoDB class by Alexandre Bergere 137
  • 138. Authentification BUSINESS NEEDS MONGODB SECURITY FEATURES Authentication SCRAM, LDAP, Kerberos, x.509 Certificates Authorization Built-in Roles, User-Defined Roles, Field-Level Redaction Auditing Admin, DML, DDL, Role-Based Encryption Network: SSL (with FIPS 140-2) Disk : Encrypted Storage Engine or Partner Solutions 06/06/2019 MongoDB class by Alexandre Bergere 138
  • 139. Localhost Exception The localhost exception allows you to enable access control and then create the first user in the system. With the localhost exception, after you enable access control, connect to the localhost interface and create the first user in the admin database. The first user must have privileges to create other users, such as a user with the userAdmin or userAdminAnyDatabase role. Changed in version 3.0: The localhost exception changed so that these connections only have access to create the first user on the admin database. In previous versions, connections that gained access using the localhost exception had unrestricted access to the MongoDB instance. The localhost exception applies only when there are no users created in the MongoDB instance and only when you’re connected to database via the localhost interface, meaning in the same server. 06/06/2019 MongoDB class by Alexandre Bergere 139
  • 140. Client/User Authentication Mechanism Mechanism Description SCRAM-SHA-1 • Default mechanism • Challenge / Response • Username / Password • IETF Standard MONGODB-CR • Challenge / Response • Replaced by SCRAM-SHA-1 • Username / Password • Deprecated as of MongoDB 3.0 X.509 • Certificate based • Introduced in MongoDB 2.6 • TLS LDAP • Lightweight Director Access Protocol • Used for directory information • External authentication mechanism Kerberos • Developed at MIT • Design for secure authentication • External authentication mechanism 06/06/2019 MongoDB class by Alexandre Bergere 140
  • 141. Client/User Authentication Initialisation mongod --auth --dbpath C:UsersalexaDocumentsMongoDBdata # Request: > use admin db.createUser( { user: "UserAdmin", pwd: "abc123", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } ) The first thing you are allowed to do when connected to an authenticated Mongo server is you’re allowed to create the firste user in the database. With that first user you create then create other users. 06/06/2019 MongoDB class by Alexandre Bergere 141
  • 142. Client/User Authentication Authentification methods After you’re created the first user in the database, the localhost exception will not apply. Always specify the database in which the user is created. mongo admin --port 27017 -u "UserAdmin" -p "abc123" OR: mongo –port 27017 -u "UserAdmin" -p "abc123" – authenticationDatabase=admin > use admin > db.auth(‘UserAdmin’, ‘abc123’ ) OR When adding a user, you create the user in a specific database. This database is the authentication database for the user. A user can have privileges across different databases; i.e. a user’s privileges are not limited to the authentication database. By assigning to the user roles in other databases, a user created in one database can have permissions to act on other databases. 06/06/2019 MongoDB class by Alexandre Bergere 142
  • 143. Client/User Authentication Informations # Returns users information: > db.getUsers() > db.system.users.find() # Returns users information for a specified user: > db.getUsers(username) 06/06/2019 MongoDB class by Alexandre Bergere 143
  • 144. Client/User Authentication Role Roles are grouped of privileges, actions over resources, that are granted to users over a given namespace (database). { role: "<name>", privileges: [ { resource: { <resource> }, actions: [ "<action>", ... ] }, ... ], roles: [ { role: "<role>", db: "<database>" } | "<role>", ... ] } 06/06/2019 MongoDB class by Alexandre Bergere 144
  • 146. Client/User Authentication Role All roles : https://docs.mongodb.com/manual/reference/bui lt-in-roles/ read : the role provides read access by granting the following actions collStats dbHash dbStats find killCursors listIndexes listCollections 06/06/2019 MongoDB class by Alexandre Bergere 146
  • 147. Client/User Authentication Action Query & Write find Insert remove update bypassDocumentValidationAll action: https://docs.mongodb.com/manual/reference/ privilege-actions/06/06/2019 MongoDB class by Alexandre Bergere 147
  • 148. Client/User Authentication Ressources resource: { db: "users" , collection: "usersCollection" ,cluster: true ,anyResource: true } 06/06/2019 MongoDB class by Alexandre Bergere 148
  • 149. Client/User Authentication Role > use admin db.createRole( { role: "myClusterwideAdmin", privileges: [ { resource: { cluster: true }, actions: [ "addShard" ] }, { resource: { db: "config", collection: "" }, actions: [ "find", "update", "insert", "remove" ] }, { resource: { db: "users", collection: "usersCollection" }, actions: [ "update", "insert", "remove" ] }, { resource: { db: "", collection: "" }, actions: [ "find" ] } ], roles: [ { role: "read", db: "admin" } ] }, { w: "majority" , wtimeout: 5000 } ) 06/06/2019 MongoDB class by Alexandre Bergere 149
  • 150. Client/User Authentication Monitoring role > use admin db.createRole( { role: "manageOpRole", privileges: [ { resource: { cluster: true }, actions: [ "killop", "inprog" ] }, { resource: { db: "", collection: "" }, actions: [ "killCursors" ] } ], roles: [] } ) db.createRole( { role: "mongostatRole", privileges: [ { resource: { cluster: true }, actions: [ "serverStatus" ] } ], roles: [] } ) 06/06/2019 MongoDB class by Alexandre Bergere 150
  • 151. Client/User Authentication Role information # Returns roles information: > db.getRoles("read", {showPrivileges:true}) # Helpful: > var readRoles = db.getRoles("read", {showPrivileges:true}) > readRoles.privileges[0] 06/06/2019 MongoDB class by Alexandre Bergere 151
  • 152. Client/User Authentication Role modification # Add a role: > db.grantRolesToUser( "reportsUser", [ { role: "read", db: "accounts" } ] ) # Revoke a role: > db.revokeRolesFromUser( “myTester", [ { role: "readWrite", db: “crunchbase" } ] ) 06/06/2019 MongoDB class by Alexandre Bergere 152
  • 153. Client/User Authentication User # Create a new user and attribute role: > db.createUser( { user: "myTester", pwd: "xyz123", roles: [ { role: "readWrite", db: "crunchbase" }, { role: "read", db: "test" } ] } ) 06/06/2019 MongoDB class by Alexandre Bergere 153
  • 154. TP – Client/User Authentication 1. Create an admin user with the role “userAdminAnyDatabase” on the database “admin”. 2. Create a user “myTester” with a reader/writer role on the database “crunchbase”. 3. Create a user “Reader” with a reader role on the database “crunchbase. 4. Export the collection “artists”, delete it and import it back. 06/06/2019 MongoDB class by Alexandre Bergere 154
  • 155. TP – Client/User Authentication 06/06/2019 MongoDB class by Alexandre Bergere 155 # 1. Create an admin user with the role “userAdminAnyDatabase” on the database “admin”. mongod --auth --port 27017 --dbpath C:UsersalexaDocumentsCoursMongoDB2017-2018datadata mongo > use admin > db.createUser( { user: "UserAdmin", pwd: "abc123", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } )
  • 156. TP – Client/User Authentication 06/06/2019 MongoDB class by Alexandre Bergere 156 # 2. Create a user “myTester” with a reader/writer role on the database “crunchbase”. mongo --port 27017 -u "UserAdmin" -p "abc123" --authenticationDatabase "admin" OR mongo > use admin > db.auth("UserAdmin", "abc123" ) > db.createUser( { user: "myTester", pwd: "xyz123", roles: [ { role: "readWrite", db: "crunchbase" } ] } )
  • 157. TP – Client/User Authentication 06/06/2019 MongoDB class by Alexandre Bergere 157 # 3. Create a user “Reader” with a reader role on the database “crunchbase. > db.createUser( { user: "myReader", pwd: "xyz123", roles: [ { role: "read", db: "crunchbase" } ] } ) # 4. Create a user “Reader” with a reader role on the database “crunchbase. mongoexport -d crunchbase -c companies –out C:UsersalexaDocumentsMongoDBsrccompanies_export.json mongoimport -d crunchbase -c companies -u "myTester" -p "xyz123" --authenticationDatabase "crunchbase" C:UsersalexaDocumentsMongoDBsrccompanies.json
  • 158. Internal Authentication Mechanism Mechanism Description Keyfile (SCRAM-SHA-1) • shared password • copy exists on each member • 6-1024 Base64 characters • whitespace ignored x.509 • certificate based • recommended to issue different certs per member Members of a replica set or sharded cluster must prove who they are. 06/06/2019 MongoDB class by Alexandre Bergere 158
  • 159. Internal Authentication Shared / ReplicaSet authentication With Keyfile access 1. Create a keyfile Create a keyfile. With keyfile authentication, each mongod instances in the replica set uses the contents of the keyfile as the shared password for authenticating other members in the deployment. Only mongod instances with the correct keyfile can join the replica set. 2. Copy the keyfile to each replica set member Copy the keyfile to each server hosting the replica set members. Ensure that the user running the mongod instances is the owner of the file and can access the keyfile. 3. Enable authentication for each member of the replica set. openssl rand -base64 756 > <path-to-keyfile> mongod --dbpath <path> --port <port> --replSet <replicaSetName> --fork --keyFile <path-to-keyfile> Update Existing Deployment 06/06/2019 MongoDB class by Alexandre Bergere 159
  • 160. Internal Authentication Shared / ReplicaSet authentication With Keyfile access 4. Add first user Add a user with the userAdminAnyDatabase role. 5. Authenticate as the user administrator 6. Create additional users as needed for your deployment > use admin > db.createUser( { user: "myUserAdmin", pwd: "abc123", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } ) > mongo --port 27017 -u "myUserAdmin" -p "abc123" -- authenticationDatabase "admin" Update Existing Deployment > db.createUser({ "user":"AdminCluster" ,"pwd":"password" ,roles:[{"role":"clusterAdmin","db":"admin"}] }) 06/06/2019 MongoDB class by Alexandre Bergere 160
  • 161. Internal Authentication Shared / ReplicaSet authentication With Keyfile access Follow replicaset & Update Existing Deployment. OR Or follow the link bellow: https://docs.mongodb.com/v3.0/tutorial/enable-internal- authentication/ (Deploy New Replica Set with Access Control) Deploy New Replica Set with Access Control 06/06/2019 MongoDB class by Alexandre Bergere 161
  • 162. Mongo DB Atlas 06/06/2019 MongoDB class by Alexandre Bergere 162
  • 163. Mongo DB Atlas DAAS : Database As A Service • Schema design • Query and index optimization • Server size selection - you must select the appropriate size of server, coupled with IO and storage capacity • Capacity planning - you must determine when you need additional capacity, typically using the monitoring telemetry provided by MongoDB Atlas, but you can make these changes with no downtime • Initiating database restores • How much you use 06/06/2019 MongoDB class by Alexandre Bergere 163
  • 164. Mongo DB Cloud Manager 06/06/2019 MongoDB class by Alexandre Bergere 164
  • 165. MongoDB Atlas vs MongoDB Cloud Manager Feature Atlas Cloud Manager Monitoring Alert API Backup Settings Maintenance Infrastructure 06/06/2019 MongoDB class by Alexandre Bergere 165
  • 166. TP - MongoDB Atlas 06/06/2019 MongoDB class by Alexandre Bergere 166
  • 167. Connector for bi 06/06/2019 MongoDB class by Alexandre Bergere 167
  • 168. Connector for bi 06/06/2019 MongoDB class by Alexandre Bergere 168
  • 169. TP – Connector for bi Follow the link : https://docs.mongodb.com/bi-connector/master 06/06/2019 MongoDB class by Alexandre Bergere 169
  • 170. MongoDB 06/06/2019 MongoDB class by Alexandre Bergere 170
  • 171. MongoDB & Hadoop 06/06/2019 MongoDB class by Alexandre Bergere 171
  • 172. MongoDB & Spark 06/06/2019 MongoDB class by Alexandre Bergere 172
  • 173. Mtools 06/06/2019 MongoDB class by Alexandre Bergere 173
  • 174. Mtools The following tools are in the mtools collection: mlogfilter : Slices log files by time, merges log files, filters slow queries, finds table scans, shortens log lines, filters by other attributes, convert to JSON mloginfo : returns info about log file, like start and end time, version, binary, special sections like restarts, connections, distinct view mplotqueries : visualize log files with different types of plots (requires matplotlib) mlogvis : creates a self-contained HTML file that shows an interactive visualization in a web browser (as an alternative to mplotqueries) mlaunch : a script to quickly spin up local test environments, including replica sets and sharded systems (requires pymongo) 06/06/2019 MongoDB class by Alexandre Bergere 174
  • 175. MongoDB Charts MongoDB Charts is the fastest and easiest way to build visualizations of MongoDB data. (beta) 06/06/2019 MongoDB class by Alexandre Bergere 175
  • 176. Change Streams More info. Change streams allow applications to access real-time data changes without the complexity and risk of tailing the oplog. Applications can use change streams to subscribe to all data changes on a collection and immediately react to them. 06/06/2019 MongoDB class by Alexandre Bergere 176
  • 177. Stitch Full access to MongoDB, declarative read/write controls, and integration with your choice of services MongoDB Stitch lets developers focus on building applications rather than on managing data manipulation code, service integration, or backend infrastructure. Whether you’re just starting up and want a fully managed backend as a service, or you’re part of an enterprise and want to expose existing MongoDB data to new applications, Stitch lets you focus on building the app users want, not on writing boilerplate backend logic. 06/06/2019 MongoDB class by Alexandre Bergere 177
  • 178. THE END 06/06/2019 MongoDB class by Alexandre Bergere 178
  • 179. Support MongoDB in action, 2nd Edition docs.mongodb.com 06/06/2019 MongoDB class by Alexandre Bergere 179