DPA Lecture 6
DPA Lecture 6
Dr Ismail Alarab
ialarab@bournemouth.ac.uk
www.bournemouth.ac.uk
Recap
- Graph Database
- Graph vs Relational
- Neo4J
- Cypher Query
Unit Attendance
Scan Me!
Lecture Outline
➢Key – Value
➢Document Databases
➢MongoDB
Key-Value
Key - Value
Example
▪ JSON: “JavaScript Object Notation” {
"name": "John",
▪ Easy for humans to write/read, easy for "age": 30,
computers to parse/generate "city": "New York"
}
▪ Objects can be nested
▪ Built on
o name/value pairs
o Ordered list of values
Example: JSON Schema and JSON
{ {
"$schema": "http://json-schema.org/draft-07/schema#", "name": "Alice",
"type": "object", "age": 25,
"properties": { "email": "alice@example.com"
"name": { "type": "string" }, }
"age": { "type": "integer"},
"email": { "type": "string"}
},
"required": ["name", "age", "email"]
}
Assuming the JSON Schema has this properties (from the previous slide):
"properties": {
"name": { "type": "string" },
"age": { "type": "integer"},
"email": { "type": "string"}
},
Document Example: {
"_id": “1",
"name": "John",
"age": 30,
}
Collection Example: [
{
"_id": “1”,
"name": "John ",
"age": 30,
},
{
"_id": “2",
"name": “Amanda",
"age": 25,
}
]
MongoDB
MongoDB
Input: db.products.save(
Without Specifying “_id”: { item: "book", qty: 40 } )
Output { "_id" :
ObjectId("50691737d386d8fadbd6b01d
"),
"item" : "book",
"qty" : 40
}
MongoDB vs SQL
MongoDB SQL
Store Unstructured Data (NoSQL) Store Structured Data
Document Tuple/Record
Collection Table/View
PK: _id Field PK: Any Attribute(s)
Uniformity not required Uniform Relation Schema
Index Index
Embedded Structure Joins
Shard Partition
Note: Sharding in MongoDB is horizontal split to store data in smaller subsets across multiple servers
Mongo Is Schema-Free
zip = { zip = {
_id: 35004, {
city: “ACMAR”, _id: 35004,
loc: [-86, 33], city: “ACMAR”,
pop: 6065, loc: [-86, 33],
State: “AL” pop: 6065,
} State: “AL”
},
council_person = {
zip_id = 35004, council_person : {
name: “John Doe", zip_id = 35004,
address: “123 Fake St.”, name: “John Doe",
Phone: 123456 address: “123 Fake St.”,
} Phone: 123456
}
}
Example 2
book = {
title: "MongoDB: The Definitive Guide",
authors: [ "Kristina Chodorow", "Mike Dirolf" ]
published_date: ISODate("2010-09-24"),
pages: 216,
language: "English",
publisher: {
name: "O’Reilly Media",
founded: "1980",
location: "CA"
}
}
One to Many Relationship - Linking
publisher = {
_id: "oreilly",
name: "O’Reilly Media",
founded: "1980",
location: "CA"
}
book = {
title: "MongoDB: The Definitive Guide",
authors: [ "Kristina Chodorow", "Mike Dirolf" ]
published_date: ISODate("2010-09-24"),
pages: 216,
language: "English",
publisher_id: "oreilly"
}
Linking vs Embedding
book = { author = {
title: "MongoDB: The Definitive Guide", _id: "kchodorow",
authors : [ name: "Kristina Chodorow“
{ _id: "kchodorow", name: "Kristina Chodorow” }, }
{ _id: "mdirolf", name: "Mike Dirolf” }
],
published_date: ISODate("2010-09-24"),
pages: 216,
language: "English"
}
student = {
_id: "joe"
name: "Joe Bookreader",
join_date: ISODate("2011-10-15"),
address: { ... }
}
book = {
_id: "123456789"
title: "MongoDB: The Definitive Guide",
authors: [ "Kristina Chodorow", "Mike Dirolf" ],
...
}
Modelling Checkouts
student = {
_id: "joe"
name: "Joe Bookreader",
join_date: ISODate("2011-10-15"),
address: { ... },
checked_out: [
{ _id: "123456789", checked_out: "2012-10-15" },
{ _id: "987654321", checked_out: "2012-09-12" },
...
]
}
CRUD: Create Read Update Delete
CRUD
db.BookLending.insertMany([
{Book:"Introduction to DBS", Reader: "Nasr", ReturnDate:"25-10-2016"},
{Book:"Don Quixote", Reader: "Nasr”, ReturnDate:”27-10-2016”},
{Book:"Patterns of enterprise application architecture", Reader: "Aboubakr", ReturnDate:"31-10-
2016"}
])
CRUD: Querying
CRUD: Querying With “AND” Condition
. Example: (AND)
db.BookLending.find(
AND Clause in MongoDB
{Book: "Introduction to DBS",
Reader: "Nasr"
})
CRUD: Querying With “OR” Condition
Example: (OR)
. OR Clause in MongoDB db.BookLending.find({
$or: [
{ Book: "Introduction to DBS"
},
{ Reader: "Nasr" }
]
})
Example: (Include/Exclude)
db.BookLending.find(
{ Reader: "Nasr" },
{ Book: 1, ReturnDate: 1, _id: 0
}
)
Example: More about Querying
.
Example: Querying
.
CRUD: Updating
.
Example: Updating ($set and $unset)
db.BookLending.updateOne(
{ Book: "Introduction to DBS", Reader: "Nasr" }, //Match first
{ $set: { ReturnDate: "30-10-2016" } } // Update the first one matching the criteria
)
db.BookLending.updateMany(
{ Reader: "Nasr" }, // Match first
{ $set: { ReturnDate: "30-10-2016" } } // Update all documents who match the criteria
)
db.BookLending.updateOne(
{ Book: "Introduction to DBS", Reader: "Nasr" },
{ $unset: { ReturnDate: "" } } // Remove a property)
CRUD: Removal
db.BookLending.deleteOne({ Reader: "Nasr" }) //Delete first document who match the criteria
● $match operator.
db.orders.aggregate([{ $match: { status: "A" }}])
● Selecting all documents where status attribute is “A”
● No aggregation yet
● Note that this is equivalent to using find operator
Aggregation Matching (Example)
db.orders.insertMany([
{ _id: 1, status: "A", amount: 50 },
{ _id: 2, status: "B", amount: 75 },
{ _id: 3, status: "A", amount: 100 },
{ _id: 4, status: "A", amount: 150 },
{ _id: 5, status: "B", amount: 200 }
])
Input code: Output:
db.orders.aggregate([ [
{ { _id: 1, status: 'A', amount: 50 },
$match: { status: "A" } { _id: 3, status: 'A', amount: 100 },
} { _id: 4, status: 'A', amount: 150 }
]) ]
Aggregation Grouping With Sum
● $group operator:
db.orders.aggregate([
{
$group: {
_id: "$status", // Group by the status field
total: { $sum: "$amount" } // Calculate the total amount for each
status group
}
}
])
● Calculating sum of amount attribute per status, showing it
as “total”.
● Specifying the attribute to group in _id. Possible to have
combinations of grouping fields.
Aggregation Grouping With Sum (Example)
db.orders.insertMany([
{ _id: 1, status: "A", amount: 50 },
{ _id: 2, status: "B", amount: 75 },
{ _id: 3, status: "A", amount: 100 },
{ _id: 4, status: "A", amount: 150 },
{ _id: 5, status: "B", amount: 200 }
])
Input code: Output:
db.orders.aggregate([{ [
$group: { { _id: 'A', total: 300 },
_id: "$status", { _id: 'B', total: 275 }
total: ]
{ $sum: "$amount" } }}])
Aggregation Grouping With Max
db.orders.aggregate([
{ $group: { _id: "$status", total: {
$sum:1} } }
])
Aggregation Grouping With Counts (Example)
db.orders.insertMany([
{ _id: 1, status: "A", amount: 50 },
{ _id: 2, status: "B", amount: 75 },
{ _id: 3, status: "A", amount: 100 },
{ _id: 4, status: "A", amount: 150 },
{ _id: 5, status: "B", amount: 200 }
])
Input code: Output:
db.orders.aggregate([{ [
$group: { _id: 'B', total: 2 },
{ _id: "$status", { _id: 'A', total: 3 }
total: {$sum:1} } } ]
])
Aggregation Projection
db.orders.insertMany([
{ "_id": 1, "product": "Phone", "type": "iOS", "quantity": 2, "price": 500 },
{ "_id": 2, "product": "Phone", "type": "iOS", "quantity": 3, "price": 600 },
{ "_id": 3, "product": "Laptop", "type": "Android", "quantity": 1, "price": 1200 },
{ "_id": 4, "product": "Laptop", "type": "Android", "quantity": 2, "price": 1000 },
{ "_id": 5, "product": "Tablet", "type": "iOS", "quantity": 3, "price": 300 }
]);
Exercise:
We are required to write an aggregation pipeline to match the product with
more than 1 quantity, group the orders by type (IOS/Android) and find the
totalRevenue of each group, project the fields “type” and “totalRevenue”
Aggregation Pipeline: By Example
Step 1:
db.orders.aggregate([
{
$match: { quantity: { $gt: 1 }
},
// To be continued
Aggregation Pipeline: By Example
Step 2:
{
$group: {
_id: "$type", // Group by type (IOS/Android)
totalRevenue: { $sum: { $multiply: ["$quantity", "$price"] } }
}
},
Aggregation Pipeline: By Example
Step 3:
{
$project: {
type: "$_id", // Rename _id to type
totalRevenue: 1, // Include the totalRevenue field
_id : 0 // Exclude _id
}
Aggregation Pipeline: By Example
Example:
db.order.find({}).pretty()
This query will retrieve all documents from the orders collection
and display them in a more structured output.
JOINS
● Wiese, Chapter 6
● Mongodb manual https://docs.mongodb.com/manual
Homework:
● Configure MongoDB on your machine
○ Either the cloud version (follow the tutorial on Brightspace)
○ Or locally
(https://docs.mongodb.com/manual/installation/#mongodb-communityedition-
installation-tutorials)
QUESTIONS?
69