Hui Hu Ph.D.
Department of Epidemiology
College of Public Health and Health Professions & College of Medicine
April 1, 2019
NoSQL Databases and Semi-structured Data Models
Introduction to MongoDB
body
h1
p
p
li
li
Extensive Markup Language
JavaScript Object Notation
[
{
_id: 1,
name: "john",
age: 21,
type: 1,
status: "A",
favorites: {artist:"Picasso",food:"pizza"},
finished: [17,3],
badges: ["blue","black"],
points: [
{points: 85, bonus: 10},
{points: 70, bonus: 5}
]
},
{
_id: 2,
name: "mike",
age: 20
}
]
One structure can be embedded in another structure
con <- mongo(collection="collectionName", db="dbName", url="url")
Similar to Table in relational databases
con <- mongo(collection="Students", db="phc7065", url="mongodb://localhost:27017")
SELECT
con$find()
{_id:1,
name:"John",
age:20,
courses: ["a","b","c"]}
{_id:1,
name:"John",
age:20,
courses: ["a","b","c"]}
_id:1,
points: [
{points: 90, bonus:10}
{points: 60, bonus:20}
]
_id:2,
points: [
{points: 53, bonus:20}
{points: 64, bonus:11}
]
_id:1,
points: [
{points: 99, bonus:17}
{points: 10, bonus:24}
]
con$count('{"age":{"$exists":true}}')
SELECT COUNT(age) FROM Students
SELECT COUNT(DISTINCT age) FROM Students
length(con$distinct('age'))
con$aggregate('[
{"$group":{"_id":"$department","meanAge":{"$avg":"$age"}}}
]')
SELECT MEAN(age) FROM Students GROUP BY department;
SELECT MEAN(age) FROM Students
WHERE course0='a' OR course1='a' OR course2='a'
GROUP BY department;
con$aggregate('[
{"$match":{"courses":{"$in":["a"]}}}
{"$group":{"_id":"$department","meanAge":{"$avg":"$age"}}}
]')
con$aggregate('[
{
"$group":{
"_id":{"department":"$department","college":"$college"},
"meanAge":{"$avg":"$age"}
}
}
]')
SELECT MEAN(age) FROM Students GROUP BY department, college;
con$aggregate('[
{"$match":{"$text":{"$search":"Miami Florida"}}},
{"$sort":{"score":{"$meta":"textScore"}}},
{"$project":{"hometown":1,"name":1}}
]')
Colleges
Students
con$aggregate('[
{
"$lookup":{
"from":"Students",
"localField":"name",
"foreignField":"college",
"as":"students"
}
}
]'')
con$aggregate('[
{
"$lookup":{
"from":"Colleges",
"localField":"college",
"foreignField":"name",
"as":"colleges"
}
}
]')
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/