Chapitre 4 MongoDB
Chapitre 4 MongoDB
SQL Vs NoSQL
NoSQL
MongoDB
Basic CRUD operations
Schema Validation
Designing Schema
SQL VS NoSQL
SQL NoSQL
distributed,
open-source,
horizontal scalable ,
schema-free,
simple API,
Column Store –
Each storage block
contains data from
only one column
Document
Store – stores
Key-Value
Store – Hash documents
made up of
table of keys
tagged
elements
5
MongoDB
What is MongoDB ?
• Scalable High-Performance Open-source,
Document-orientated database.
No complex joins
Built on
• name/value pairs
• Ordered list of values
http://json.org/
13
BSON
“Binary JSON”
Goals
• Lightweight
• Traversable
• Efficient (decoding and encoding)
http://bsonspec.org/
14
BSON Example
{
"_id" : "37010"
“City" : “Nashik",
“Pin" : 423201,
"state" : “MH",
“Postman” : {
name: “Ramesh Jadhav”
address: “Panchavati”
}
} 15
Data Types of MongoDB
Integer
Date Boolean
Object ID String
Null Arrays 16
Data Types
String : This is most commonly used datatype to store the data. String in
mongodb must be UTF-8 valid.
Integer : This type is used to store a numerical value. Integer can be 32
bit or 64 bit depending upon your server.
Boolean : This type is used to store a boolean (true/ false) value.
Double : This type is used to store floating point values.
Min/ Max keys : This type is used to compare a value against the lowest
and highest BSON elements.
Arrays : This type is used to store arrays or list or multiple values into one
key.
Timestamp : ctimestamp. This can be handy for recording when a
document has been modified or added.
Object : This datatype is used for embedded documents.
17
Data Types
db
• To check currently selected database use the
command db
show dbs
• Displays the list of databases
db.dropDatabase()
19
• To Drop the database
Basic Database Operations- Collection
db.createCollection (name)
• To create collection: Ex:- db.createCollection(Stud)
show collections
• List out all names of collection in current database
db.databasename.insert({Key : Value})
db.collection.drop()
db.Stud.drop()
CRUD Operations
Insert
Find
Update
Delete
21
Schema validation
MongoDB can perform schema validation during
updates and insertions. Existing documents do not
undergo validation checks until modification.
validator: specify validation rules or expressions for
the collection
validationLevel: determines how strictly MongoDB db.createCollection( <name>,
applies validation rules to existing documents during {validator: <document>,
an update validationLevel: <string>,
strict, the default, applies to all changes to any document validationAction: <string>,
of the collection
})
moderate, applies only to existing documents that
already fulfill the validation criteria or to inserts
validationAction: determines whether MongoDB should
raise error and reject documents that violate the
validation rules
or warn about the violations in the log but allow invalid
documents
22
JSON Schema Validation
Starting in version 3.6, MongoDB supports JSON Schema validation
specific type of schema validation that strictly adheres to the JSON Schema standard
db.createCollection("students",
{ validator: {
$jsonSchema: {
bsonType: "object",
required: [ "name", "year" ],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
year: {
bsonType: "int",
minimum: 2000,
maximum: 2099,
description: "must be an integer in [2000, 2099] and is
required»
23
}}}}})
Designing Schema
26
Designing Schema: Hybride
Example: Social Media User Profiles
Users Collection:
{
_id: ObjectId("user123"),
it’s possible to combine both approaches name: "John Doe",
email: "[email protected]",
by embedding frequently accessed or posts: [
{
summary data and referencing the rest: postId: ObjectId("post123"),
title: "My First Post",
High Read Performance for Common preview: "This is a short summary of my first post..."
},
Data: Embed frequently accessed {
postId: ObjectId("post456"),
fields for speed while referencing less title: "A Day in the Life",
preview: "Sharing some thoughts about today..."
commonly used data. }
]
}
Handling Both Scalability and
Posts Collection (Referenced for Full Content):
Performance: Allows flexible design {
_id: ObjectId("post123"),
for large-scale systems. title: "My First Post",
content: "This is the full content of the first post...",
createdAt: ISODate("2024-11-21T10:00:00Z")
} 27